Redis订阅发布操作

 
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        

        
            org.redisson
            redisson
            3.7.0
        

        
            org.springframework.boot
            spring-boot-starter-jta-atomikos
        

        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.1.1
        
        
            com.alibaba
            druid
            1.1.10
        

        
            org.springframework.boot
            spring-boot-starter-data-jpa
        

        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            mysql
            mysql-connector-java
            5.1.40
        
        
            com.oracle
            ojdbc6
            11.2.0.3
        

        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        
        
        
            redis.clients
            jedis
            2.9.0
        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.10
        
        
            mysql
            mysql-connector-java
            5.1.47
        
        
        
            com.alibaba
            fastjson
            1.2.46
        

redis基本配置:

package com.example.redistempalte.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
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.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class MyRedisConf {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory){
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(factory);
        //key序列化
        RedisSerializer keySerializer = new StringRedisSerializer();
        RedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setKeySerializer(keySerializer);
        //value序列化
        redisTemplate.setValueSerializer(valueSerializer);
        //hash key 序列化
        redisTemplate.setHashKeySerializer(keySerializer);
        //hash value 序列化
        redisTemplate.setHashValueSerializer(valueSerializer);
        //redis初始化
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    public RedisTemplate redisTemplateGroup(RedisConnectionFactory factory) {
        // 配置redisTemplate
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(factory);
        RedisSerializer keySerializer = new StringRedisSerializer();
        RedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer(getMapper());
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * 获取JSON工具
     * @return
     */
    private final ObjectMapper getMapper() {
        ObjectMapper mapper = new ObjectMapper();
        //将类名称序列化到json串中,去掉会导致得出来的的是LinkedHashMap对象,直接转换实体对象会失败
        //设置输入时忽略JSON字符串中存在而Java对象实际没有的属性
        //其中该配置,需要升级fasterxml版本
        //mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }
}

消息发布:

package com.example.redistempalte.Publisher;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;

@Component
public class MsgPublisher {

    private Logger logger = LoggerFactory.getLogger(MsgPublisher.class);

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ChannelTopic topic;
    //private ChannelTopic topic=new ChannelTopic("pubsub:queue");

    public void sendMsg(String msg){
        redisTemplate.convertAndSend( "pubsub:queue", "Message: " + msg +
                ";Time:" + Calendar.getInstance().getTime());
    }
}

消息发布配置

package com.example.redistempalte.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.listener.ChannelTopic;

@Configuration
public class PubConfig {

    /**
     * 订阅发布的主题
     * @return
     */
    @Bean
    ChannelTopic topic() {
        return new ChannelTopic( "pubsub:queue" );
    }
}

消息订阅

package com.example.redistempalte.Listener;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

@Component
public class MsgListener implements MessageListener {

    @Override
    public void onMessage(Message message, byte[] bytes) {
        System.out.println("Message received: " + message.toString());
    }
}

消息订阅配置

package com.example.redistempalte.config;

import com.example.redistempalte.Listener.MsgListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
public class SubConfig {

    //消息监听适配器
    @Bean
    MessageListenerAdapter messageListener() {
        return new MessageListenerAdapter( new MsgListener() );
    }
    //消息监听容器
    /*
    RedisMessageListenerContainer
    其实现了InitializingBean, DisposableBean, BeanNameAware, SmartLifecycle几个接口
    InitializingBean:主要实现afterPropertiesSet方法,来定义spring设置完properties后进行的处理,在spring init这个bean时候会被调用
    DisposableBean:实现destroy方法,在spring销毁bean时会调用
    BeanNameAware:实现setBeanName方法来为bean进行取名,在RedisMessageListenerContainer中该name被用于内部线程的线程名
    SmartLifecycle:spring的bean生命周期类,spring会调用start,stop等操作来完成RedisMessageListenerContainer类的启动
     */
    @Bean
    RedisMessageListenerContainer redisContainer(RedisConnectionFactory factory) {
        final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        container.addMessageListener(messageListener(), new ChannelTopic( "pubsub:queue" ));
        return container;
    }
}

Controller:

package com.example.redistempalte.controller;

import com.example.redistempalte.Publisher.MsgPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RedisTestController {

    @Autowired
    private MsgPublisher msgPublisher;

    @RequestMapping("/sendMsg")
    @ResponseBody
    public String sendMsg(@RequestParam("msg") String msg){
        msgPublisher.sendMsg(msg);
        return "发送成功!";
    }
}

你可能感兴趣的:(Redis订阅发布操作)