记录学习
redis发布订阅
1.创建配置类
package com.live.server.config;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
/**
* 作者:Lelouch
* 时间:2020/11/1214:20
*/
@Configuration
@EnableCaching
public class RedisSubListenerConfig {
//初始化监听器
@Bean
public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter,
MessageListenerAdapter messageListenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("live-server/chat/websocket"));
container.addMessageListener(messageListenerAdapter, new PatternTopic("live-server/chat/userMap"));
return container;
}
//利用反射来创建监听到消息之后的执行方法
//WebSocket 类 下的receiveMessage
@Bean
public MessageListenerAdapter listenerAdapter(WebSocket webSocket) {
return new MessageListenerAdapter(webSocket, "receiveMessage");
}
//利用反射来创建监听到消息之后的执行方法
//WebSocket 类 下的receiveLivePeople
@Bean
public MessageListenerAdapter messageListenerAdapter(WebSocket webSocket) {
return new MessageListenerAdapter(webSocket, "receiveLivePeople");
}
@Bean
StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
}
2.发布消息
String channel = "live-server/chat/userMap";
stringRedisTemplate.convertAndSend(channel,s);
3.接收消息
public void receiveLivePeople(String s) {
//这里是收到通道的消息之后执行的方法
try {
if(s!=null){
Gson gson = new Gson();
Map<String, Long> map = new HashMap<String, Long>();
map = gson.fromJson(s, map.getClass());
Long roomId = Long.parseLong(String.valueOf(map.get("roomId")));
if(rooms.get(roomId)!=null){
for (Session session : rooms.get(roomId)) {
session.getBasicRemote().sendText(s);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}