使用window 版本的redis
1.打开一个 cmd 窗口 使用cd命令切换目录到redis安装目录下 运行 redis-server.exe redis.windows.conf
2.这时候另启一个cmd窗口,还是切换到redis安装目录下,原来的不要关闭,不然就无法访问服务端了
输入:redis-cli.exe -h 127.0.0.1 -p 6379
进入127.0.0.1表示访问成功
spring boot 项目导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
注册redis消息监听器容器,并且订阅消息
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
@Configuration
public class MyRedisConfig {
@Bean
public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("mytopic"));
return container;
}
/**
* 绑定消息监听者和接收监听的方法,必须要注入这个监听器,不然会报错
*/
@Bean
public MessageListenerAdapter listenerAdapter(){
return new MessageListenerAdapter(new Receiver(),"receiveMessage");
}
class Receiver {
public void receiveMessage(String message) {
System.out.format("Received <%s>%n",message);
}
}
}
发布消息
@RestController
public class TestController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
@RequestMapping("test_redis")
public String testRedis(){
String name = stringRedisTemplate.opsForValue().get("name");
return name;
}
*/
@RequestMapping("publish")
public String publish(){
for(int i=1;i<=10;i++){
stringRedisTemplate.convertAndSend("mytopic", "这是我发第"+i+"条的消息啊");
}
return "结束";
}
}
spring boot 官方有对redis 发布订阅做介绍
https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#pubsub