如何访问位于@service类中的sseemitter集合

m2xkgtsf  于 2021-07-22  发布在  Java
关注(0)|答案(1)|浏览(341)

这个 sses Map已从messagecontroller类移动到用@service注解的类 MessageTemplate.class . 现在我们需要一种方法 SseEmitter 示例(在内部创建) openConn() )到messagetemplate类内部的Map。
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<>();
..
}
zujrkrfu

zujrkrfu1#

假设问题中呈现的所有抽象都是“自定义”(在您的组织中编写的代码),它们本身不属于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); 
     }  
}

相关问题