sses
映射已从MessageController类移动到用@ServiceMessageTemplate.class
注释的类。现在,我们需要一种方法来将SseEmitter
实例(在openConn()
中创建(添加到MessageTemplate类中的sses映射中。
Map在这里可能不是最好的选择,如果是的话,还有什么其他缓存替代方案可用,因为我需要一个away来将消息发送回各个客户端?
@Controller
@RequestMapping(value="/")
public class MessageController{
@Autowired MessageOperations mesgOps;
//Moved to MessageTemplate
Map<String, SseEmitter> sses = new ConcurrentHashMap<>();
@GetMapping(value = "/conn/{username}")
public SseEmitter openConn(@PathVariable("username") String username){
SseEmitter sseEmitter = new SseEmitter(3600000L);
sses.put(username, sseEmitter);
return sseEmitter;
}
@Service
public class MessageTemplate implements MessageOperations{
//The above map now resides here.
Map<String, SseEmitter> sses = new ConcurrentHashMap<>();
..
}
假设问题中所有呈现的抽象都是"自定义"的(在您的组织中编写的代码(,并且它们本身不属于spring生态系统,我看到以下内容:
MessageTemplate
是由spring驱动的单例作用域bean- 控制器也是一个单例bean
MessageOperations
接口是用于注入的自定义接口
在这种情况下,明显的变化是:
interface MessageOperations {
SseEmitter associateSseEmitterWithUser(String userName);
}
@Service
public class MessageTemplate implements MessageOperations {
private Map<String, SseEmitter> sses = new ConcurrentHashMap<>();
// other existing code you might already have
public SseEmitter associateSseEmitterWithUser(String username) {
SseEmitter sseEmitter = new SseEmitter(3600000L);
sses.put(username, sseEmitter);
return sseEmitter;
}
}
@Controller
@RequestMapping(value = “/“)
public class MessageController {
@Autowired MessageOperations mesgOps;
@GetMapping(value=“/conn/{username})
public SseEmitter openConn(@PathVariable(“username”) String username) {
return mesgOps.associateSseEmitterWithUser(username);
}
}