SpringBoot RedisTemplate 发布订阅

使用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值