Disclaimer: Reference article: 75471012?locationnum=2&fps=1
• Using Maven to introduce a Redis launcher into your project
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactid>spring-boot-starter-data-redis</artifactid >
</dependency>
Two. Register a REDIS message listener class
@Configuration Public classRedissublistenerconfig {//different channel names Private Static FinalString channel = "Testchannel"; Private Static FinalString Channel2 = "Chat"; /*** 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//equivalent to a bean in XMLredismessagelistenercontainer Container (redisconnectionfactory connectionfactory, Messagelisteneradapter listeneradapter,messagelisteneradapter listenerAdapter2) {Redismessagelistenerco Ntainer Container=NewRedismessagelistenercontainer (); Container.setconnectionfactory (ConnectionFactory); //subscribed to a channel called Testchannel.Container.addmessagelistener (ListenerAdapter,Newpatterntopic (Redissublistenerconfig.channel)); //subscribed to a channel called chatContainer.addmessagelistener (ListenerAdapter2,Newpatterntopic (Redissublistenerconfig.channel2)); returncontainer; } /*** Message Listener adapter, binding message Processor, invoking the message processor's business method using reflection technology *@paramReceiver *@return */@Bean messagelisteneradapter listeneradapter (messagereceiver receiver) {return NewMessagelisteneradapter (receiver, "ReceiveMessage"); } @Bean messagelisteneradapter ListenerAdapter2 (messagereceiver receiver) {return NewMessagelisteneradapter (receiver, "ReceiveMessage2"); } /**template for Redis read content*/@Bean stringredistemplate Template (redisconnectionfactory connectionfactory) {return Newstringredistemplate (connectionfactory); }}
Three · Writing classes that handle subscription messages
@Component Public class messagereceiver { /** method for receiving Messages */public void ReceiveMessage (String message) { System.out.println ("received a message:" +message); } /** methods for receiving messages */ Public void receiveMessage2 (String message) { System.out.println ("received a message 2:" +message);} }
Four. Start the program and send messages to the Redis chat and Testchannel channels to hear
Using messages from multiple channels subscribed to Redis in SpringBoot2.0