Java Spring数据-Spring引导findFirst检索同一文档两次
我在MongoDB中使用SpringBoot和SpringData 这是一个带有Java Spring数据-Spring引导findFirst检索同一文档两次,java,spring,mongodb,spring-boot,spring-data-mongodb,Java,Spring,Mongodb,Spring Boot,Spring Data Mongodb,我在MongoDB中使用SpringBoot和SpringData 这是一个带有@RestController注释的REST服务。它调用另一个组件,即ChuckNorrisCommand: @Component public class ChuckNorrisCommand extends AbstractCommand { /** * command name. */ private static final String CHUCK_COMMAND_NA
@RestController
注释的REST服务。它调用另一个组件,即ChuckNorrisCommand
:
@Component
public class ChuckNorrisCommand extends AbstractCommand {
/**
* command name.
*/
private static final String CHUCK_COMMAND_NAME = "chuck";
/**
* repository to retrieve data form DB.
*/
@Autowired
private ChuckNorrisRepository chuckNorrisRepository;
/**
* repository to access gif from db.
*/
@Autowired
private ChuckNorrisGifRepository gifRepository;
/**
* main method for the command.
* @param request the request object that triggered the command
* @return a quote
*/
@Override
public final ResponseToSlack executeCommand(final SlackRequest request) {
final ChuckNorrisQuote chuckQuote = this.chuckNorrisRepository.findFirstByLastDisplayedDateIsNullOrderByRankAsc();
chuckQuote.setLastDisplayedDate(new Date());
this.chuckNorrisRepository.save(chuckQuote);
final List<ChuckNorrisGif> all = this.gifRepository.findAll();
final int randomIndex = (int)(Math.random() * (((all.size() - 1)) + 1));
final StringBuilder out = new StringBuilder();
out.append(chuckQuote.getQuote()).append(" <").append(all.get(randomIndex).getUrl()).append('>');
return new ResponseToSlack(ResponseTypeEnum.IN_CHANNEL, out.toString());
}
/**
* Command name.
* @return command name.
*/
@Override
public final String getName() {
return CHUCK_COMMAND_NAME;
}
/**
* Command description.
* @return command description.
*/
@Override
public final String getDescription() {
return "Get a very nice Chuck Norris quote and a gif to go with it.";
}
}
我遇到的问题是ChuckNorrisRepository
。当我在本地测试时,对服务的每个调用都有预期的行为:我从MongoDB集合中获得一个新文档
但在我的“生产”环境中部署时,需要对服务进行两次调用才能获得不同的文档。这是可复制的,需要两次调用才能得到一个新文档
我激活了MongoDB连接器日志,我确实看到每个服务调用都会执行请求。由于文档已更新,我还能够检查集合是否已正确更新,因此对我来说,问题在于数据检索和数据表示之间
我注意到这两种环境之间的主要区别(坦率地说,我不知道它为什么会这样)当我在我的计算机上启动SpringBoot可执行jar时,我得到的tomcat只有一个线程,但在生产环境中,我有34个线程在为SpringBoot应用程序运行
我真的到了一个地步,我不知道在互联网上寻找什么,也不知道要测试什么才能对正在发生的事情有更多的了解
谢谢你的时间和智慧
编辑:解决方法
我把机制改为使用计数器而不是日期,现在它可以正常工作了。
我可能应该向spring报告这件事,因为我真的不知道发生了什么。在lighter note
ChuckNorrisRepository
将按照自己的意愿做任何事情:)您如何呼叫服务器端?您使用JQuery吗?有时候JQuery会发送多个调用。。如果您使用的是JQuery,请尝试使用event.stopImmediatePropagation()
。更多信息请点击此处:。我希望是这样useful@Bond-JavaBond:我曾在某个时候期待过类似的事情:)@AngeloImmediata:Nope,普通的老cURL
命令从shell在两种情况下执行(本地和生产)
public interface ChuckNorrisRepository extends MongoRepository<ChuckNorrisQuote, ObjectId> {
ChuckNorrisQuote findFirstByLastDisplayedDateIsNullOrderByRankAsc();
}