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

 

你可能感兴趣的:(springboot,redis)