- 当订阅了一个频道,向该频道里面发送消息,订阅这个频道的人就可以接收到消息,但是不支持持久化,redis宕机,网络错误就会消息丢失
- 需要四个类就可以了
- 第一步:初始化RedisTemplate
@Component
public class InitRedisTemplate {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(RedisSerializer.string());
return redisTemplate;
}
}
- 第二步:订阅频道,(频道写在配置文件当中,方便扩展)
@Slf4j
@RequiredArgsConstructor
@Configuration
public class Config {
private final MessageListener messageListener;
@Bean
RedisMessageListenerContainer redisContainer(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
List<Topic> list = new ArrayList<>();
list.add(new PatternTopic("ZHOU"));
list.add(new PatternTopic("DA"));
list.add(new PatternTopic("TOU"));
container.addMessageListener(messageListener, list);
return container;
}
}
@Component
@Slf4j
public class RedisMessageListener implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
log.info(message.toString());
}
}
@Controller
@RequestMapping("redis")
public class RedisController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping(value = "send")
public void send(){
String message = "zhou";
redisTemplate.convertAndSend("ZHOU", JSONObject.toJSONString(message));
redisTemplate.convertAndSend("DA", JSONObject.toJSONString(message));
redisTemplate.convertAndSend("TOU", JSONObject.toJSONString(message));
}
}
- 结构图
- pom.xml文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.72</version>
</dependency>
|