Redis之PubSub和在springboot2中的使用

mac2022-06-30  243

二、springboot2中redis订阅者和发布者的使用: **

package com.example.shopgoods.controller.redisTest;

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.MessageListener; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.listener.PatternTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;

/**  * @Author: zp  * @Date: 2019/4/28 13:31  * @Description:  */ @RestController @RequestMapping("/redis") public class RedisPub_Sub_TestController {

    @Autowired     private StringRedisTemplate redisTemplate;

    /**      * 发布者      * @param message      */     @PostMapping("/publish")     public void publish(@RequestParam(value = "message") String message) {         redisTemplate.convertAndSend("news", message);

    }

    /**      * subscribe 订阅者      */     class MyRedisChannelListener implements MessageListener {         @Override         public void onMessage(Message message, byte[] pattern) {             byte[] channel = message.getChannel();             byte[] body = message.getBody();

            try {                 String content = new String(body,"UTF-8");                 String address = new String(channel,"UTF-8");                 System.out.println("get " + content + " from " + address);             } catch (UnsupportedEncodingException e) {                 e.printStackTrace();             }         }     }

    @Bean     MessageListenerAdapter messageListenerAdapter() {         return new MessageListenerAdapter(new MyRedisChannelListener());     }

    @Bean     RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {         RedisMessageListenerContainer container = new RedisMessageListenerContainer();         container.setConnectionFactory(connectionFactory);         // news 频道名称         container.addMessageListener(listenerAdapter, new PatternTopic("news"));         return container;     }

}

原文链接:https://blog.csdn.net/qq_15199097/article/details/89637254


最新回复(0)