There are many ways of asynchronous messaging, and this blog describes how to use Redis for publishing subscriptions.
Only three files are required to complete this example
1.redis Message Listener Configuration
@Configuration Public classRedislistenerconfig {/*** REDIS Message Listener container * Can add multiple Redis listeners listening to different topics, only need to bind the message listener and the corresponding message subscription processor, the message listener * through the Reflection Technology call message subscription processor related methods for some business processing * @paramConnectionFactory *@paramListenerAdapter *@return */@Bean redismessagelistenercontainer container (redisconnectionfactory connectionfactory, Messagelisteneradapter listeneradapter) {Redismessagelistenercontainer container=NewRedismessagelistenercontainer (); Container.setconnectionfactory (ConnectionFactory); //multiple MessageListener can be addedContainer.addmessagelistener (ListenerAdapter,NewPatterntopic ("Index")); returncontainer; } /*** Message Listener adapter, binding message Processor, invoking the message processor's business method using reflection technology *@paramRedisreceiver *@return */@Bean messagelisteneradapter listeneradapter (redisreceiver redisreceiver) {System.out.println ("The message adapter is in."); return NewMessagelisteneradapter (Redisreceiver, "ReceiveMessage"); } //to initialize the Redis action template with the default factory@Bean stringredistemplate Template (redisconnectionfactory connectionfactory) {return Newstringredistemplate (connectionfactory); }}
2. Message Processing
@Service Public class Redisreceiver { publicvoid receiveMessage (String message) { SYSTEM.OUT.PRINTLN ("message came:" + message); // here is the method that executes after receiving a message from the channel }}
3. A timer to send messages
// Timer @EnableScheduling @component Public class Testsendercontroller { @Autowired private stringredistemplate stringredistemplate; // Publish message to Redis Message Queue index channel @Scheduled (fixedrate = +) publicvoid sendMessage () { stringredistemplate.convertandsend ("index", String.valueof (Math.random ()));} }
Run results
This blog address: https://gitee.com/zhao-baolin/redis-message
Spring Boot uses Redis for publishing subscriptions