RedisTemplate订阅发布实例

本文详细介绍了如何在Spring Boot应用中通过pom.xml引入并配置Spring Data Redis,实现Redis连接、多数据库切换,以及Redis消息监听和消费者示例。涵盖了RedisTemplate的创建、连接池初始化和消息监听容器的配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       1.pom.xml导入jar依赖

<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-redis</artifactId>
   <version>1.6.2.RELEASE</version>
</dependency>

 

2.连接redis
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class RedisConfig {

    //redis地址
    @Value("${distdb.redis.host}")
    private String host;

    //redis端口号
    @Value("${distdb.redis.port}")
    private int port;

    //redis密码
    @Value("${distdb.redis.password}")
    private String password;

    //默认数据库
    private int defaultDB;

    //多个数据库集合
    @Value("#{'${distdb.redis.dbs}'.split(',')}")
    private List<Integer> dbList;

    //RedisTemplate实例
    private static Map<Integer, RedisTemplate<String, Object>> redisTemplateMap = new HashMap<>();

    /**
     * 初始化连接池
     */
    @PostConstruct
    public void initRedisTemplate() {
        defaultDB = dbList.get(0);//设置默认数据库
        for (Integer db : dbList) {
            //存储多个RedisTemplate实例
            redisTemplateMap.put(db, redisTemplate(db));
        }
    }

    public LettuceConnectionFactory redisConnection(int db) {
        RedisStandaloneConfiguration server = new RedisStandaloneConfiguration();
        server.setHostName(host); // 指定地址
        server.setDatabase(db); // 指定数据库
        server.setPort(port); //指定端口
        server.setPassword(RedisPassword.of(password)); //指定密码
        LettuceConnectionFactory factory = new LettuceConnectionFactory(server);
        factory.afterPropertiesSet(); //刷新配置
        return factory;
    }

    //RedisTemplate模板
    public RedisTemplate<String, Object> redisTemplate(int db) {
        //为了开发方便,一般直接使用<String,Object>
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnection(db)); //设置连接
        //Json序列化配置
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        //String的序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        //key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        //hash的key采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        //value序列化方式采用jackson
        template.setValueSerializer(stringRedisSerializer);
        //hash序列化方式采用jackson
        template.setHashValueSerializer(stringRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 指定数据库进行切换
     * @param db  数据库索引
     * @return
     */
    public RedisTemplate<String, Object> getRedisTemplateByDb(int db) {
        return redisTemplateMap.get(db);
    }

    /**
     * 使用默认数据库
     *
     * @return
     */
    public RedisTemplate<String, Object> getRedisTemplate() {
        return redisTemplateMap.get(defaultDB);
    }
}

 

3.redis消息监听

import com.ssish.saas.as.constant.RedisConstant;
import com.ssish.saas.as.message.PolicySupport;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
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.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
@AutoConfigureAfter({PolicySupport.class})
public class RedisPubSubConfig {

    //MessageListenerAdapter 表示监听频道的订阅者,可以多个
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter adapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //订阅频道,可以订阅多个
        container.addMessageListener(adapter, new PatternTopic("policy_success"));
        

        return container;
    }


    //表示监听一个频道
    @Bean
    public MessageListenerAdapter adapter(PolicySupport messageReceiver) {
         //这个地方 是给messageListenerAdapter 传入一个消息接受的处理器,利用反射的方法调用“PolicySupport 的 onMessage 方法”
        return new MessageListenerAdapter(messageReceiver, "onMessage");
    }

4.消费者

import com.ssish.saas.as.constant.RedisConstant;
import com.ssish.saas.as.schedule.databack.DatabackService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class PolicySupport implements MessageListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DatabackService databackService;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        RedisSerializer<String> redisSerializer = redisTemplate.getStringSerializer();
        String policyId= redisSerializer.deserialize(message.getBody());
        System.out.println("===========保单回传通道接收消息,policyId="+policyId);
        if(StringUtils.isNotBlank(policyId)){
            policyId = policyId.replace("\"", "");
        }
        String channel = redisSerializer.deserialize(message.getChannel());
        if(RedisConstant.POLICY_SUCCESS.equals(channel)){
            databackService.policyDataBackById(Integer.valueOf(policyId));
        }
    }

}

 5.发布消息

redisTemplate.convertAndSend("policy_success", "123456");

 

 订阅多个频道和监听多个频道参考https://www.cnblogs.com/liuyp-ken/p/10538658.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值