随着了解了Redis入门(五)—— 发布与订阅
尝试将redis和SpringBoot进行集成构建了一个简单的demo
一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
二、编码
2.1 定义接收信息接口
@Component
public interface RedisMsg {
void recevierMsg(String content);
}
2.2 消息处理类
实现RedisMsg接口
@Component
public class RedisChannelSub implements RedisMsg {
@Override
public void recevierMsg(String content) {
System.out.println("Channel频道收到消息:"+content);
}
}
@Component
public class CRMChannelSub implements RedisMsg {
@Override
public void recevierMsg(String content) {
System.out.println("CRM频道收到消息:"+content);
}
}
2.3 配置redis消息监听器
@Configuration
@EnableCaching
public class RedisListenerConfig {
/**
* redis消息监听器容器
*/
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory){
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
//订阅了channel通道
container.addMessageListener(listenerAdapter(new RedisChannelSub()),new PatternTopic("channel"));
//订阅了crm通道
container.addMessageListener(listenerAdapter(new CRMChannelSub()),new PatternTopic("crm"));
return container;
}
/**
* 配置消息处理类
* @param redisMsg
* @return
*/
@Bean
@Scope("prototype")
MessageListenerAdapter listenerAdapter(RedisMsg redisMsg){
return new MessageListenerAdapter(redisMsg,"recevierMsg");
}
}
2.4 定义消息发布者
@RestController
public class RedisPublisher {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@RequestMapping("/issue")
public void issue(@RequestParam("channel") String channel,@RequestParam("content") String content){
stringRedisTemplate.convertAndSend(channel,content);
}
}
三、示例
向channel频道发送信息


向crm频道发送信息



本文介绍了如何在SpringBoot应用中集成Redis,实现消息发布与订阅功能,包括定义接收消息接口、创建消息处理类、配置Redis消息监听器和定义消息发布者。通过实例演示了如何向channel和crm频道发送信息。
346

被折叠的 条评论
为什么被折叠?



