springboot 实现redis发布、订阅

参考官网指导:Messaging with Redis

redis发布命令

redis 127.0.0.1:6379> PUBLISH redisChat "Redis is a great caching technique"

(integer) 1

publish 频道名称 消息内容

订阅命令

redis 127.0.0.1:6379> SUBSCRIBE redisChat

Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "redisChat"
3) (integer) 1

subcribe [频道名称]

 

消息发送端


@Component
public class Sender extends Thread{

	@Resource
	private StringRedisTemplate redisCliet;
	
	public void run(){
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		try{
			while(true){
				String line = reader.readLine();
				System.out.println("发送消息:" + line);
				redisCliet.convertAndSend("chat", line);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void startService(){
		start();
	}
	
	
}

 

消息接收

@Component
public class Receiver{
	
	public void onMessage1(String msg){
		System.out.println("收到消息:" + msg.toString());
	}
}

Receiver可以不继承MessageListenerAdapter, 可以把receiver对象装饰到MessageListenerAdapter实例中,当MessageListenerAdapter的onMessage收到消息后,反射调用onMessage1方法

@SpringBootApplication
@ComponentScan(basePackages={"com.xy.mongodb"})
public class MongodbApplication {

	@Bean
	public RedisMessageListenerContainer container(Receiver receiver, RedisConnectionFactory factory){
		System.out.println("添加接收者" + receiver);
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(factory);
		MessageListenerAdapter adapter = new MessageListenerAdapter(receiver, "onMessage1");
		container.addMessageListener(adapter, new PatternTopic("chat"));
		adapter.afterPropertiesSet();
		return container;
	}
	
	
	public static void main(String[] args) {
		ApplicationContext ctx = SpringApplication.run(MongodbApplication.class, args);
		Sender sender = ctx.getBean(Sender.class);
		sender.startService();
	}
}

看MessageListenerAdapter的源码:反射调用传入的方法名

@Override
	public void onMessage(Message message, @Nullable byte[] pattern) {
		try {
			// Check whether the delegate is a MessageListener impl itself.
			// In that case, the adapter will simply act as a pass-through.
			if (delegate != this) {
				if (delegate instanceof MessageListener) {
					((MessageListener) delegate).onMessage(message, pattern);
					return;
				}
			}

			// Regular case: find a handler method reflectively.
			Object convertedMessage = extractMessage(message);
			String convertedChannel = stringSerializer.deserialize(pattern);
			// Invoke the handler method with appropriate arguments.
			Object[] listenerArguments = new Object[] { convertedMessage, convertedChannel };

			invokeListenerMethod(invoker.getMethodName(), listenerArguments);
		} catch (Throwable th) {
			handleListenerException(th);
		}
	}

 

运行结果:

sdfasdf
发送消息:sdfasdf
收到消息:sdfasdf
2018-09-06 14:09:48.562  INFO 142504 --- [on(2)-127.0.0.1] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
2018-09-06 14:09:48.562  INFO 142504 --- [on(2)-127.0.0.1] ConfigServletWebServerApplicationContext : Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@37fb0bed: startup date [Thu Sep 06 14:09:39 CST 2018]; root of context hierarchy
2018-09-06 14:09:48.564  INFO 142504 --- [on(2)-127.0.0.1] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 2147483647
2018-09-06 14:09:48.566  INFO 142504 --- [on(2)-127.0.0.1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值