构建此并发问题的正确方法是什么?春季启动

时间:2017-11-03 13:21:53

标签: java spring spring-mvc spring-boot

我正在使用Spring Boot构建一个非常简单的游戏。游戏所需的功能之一是能够同时处理多个游戏。

所以在我的控制器中,我有这些方法。

@Controller
@EnableAutoConfiguration
public class GameController {

private final GameService gameService;

@Autowired
 public GameController(final GameService gameService) {
 this.gameService = gameService;
 }

@RequestMapping("/createGame")
@ResponseBody
public String createGameController(@RequestParam(value = 
"playerName") final List<String> playerNames) {
 final String gameId = gameService.createGameAndGenerateGameId(playerNames);
 return "Your gameId is = " + gameId + " \n Give this to other users to  
 challenge!";
  }

因此,上述方法仅负责创建游戏并返回每个游戏都独一无二的“gameId”。我希望每次请求都会发生新的gameId返回。目前正在发生的是每个请求都在“共享”同一个gameId。

我知道这可以通过为每个请求手动实现新的线程来解决,但有没有弹簧方式来做到这一点?

@RequestMapping("/startGame")
@ResponseBody
 public String startGameController(@RequestParam(value = 
 "gameId") 
 final String gameId) {
    return gameService.startGame(gameId);
 }

另一个特色。因此,当我想要在游戏中执行动作时,他们对于他们指定的游戏具有特定的游戏ID。现在,如果有多个线程包含单独的游戏。如何将特定gameId映射到线程中的特定游戏?

示例:

有三个游戏在三个不同的主题上运行。

游戏1 /主题1:id = 123

游戏2 /主题2:id = 321

游戏3 /主题3:id = 213

客户端1发送/ startGame?gameId = 321

如何指定客户端1请求游戏2 /线程2?春天是否有这方面的功能,还是必须在没有弹簧的情况下完成?

感谢阅读。

1 个答案:

答案 0 :(得分:0)

默认情况下,每个请求都在一个单独的线程中执行。我假设对于每个新游戏,您通过递增计数器来创建游戏ID。要使其线程安全,请使用AtomicLong或代替数字ID创建UUID。

关于第二部分,没有内置的内容。为什么每个游戏都需要在一个单独的线程中运行?

相关问题