spring data redis实现发布订阅

依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>

配置

#Redis配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
# 连接超时时间(毫秒)
spring.redis.timeout=10000
# Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0

RedisConfiguration

package com.springboot.utils;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
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.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfiguration {

    @Bean
    public RedisTemplate<String, Object> redisCacheTemplate(LettuceConnectionFactory lettuceConnectionFactory) {

        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        //序列化方法
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.setConnectionFactory(lettuceConnectionFactory);
        return template;
    }
    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }
}

1、发布

一个springboot定时线程,每5s发布一次消息。

package com.springboot.thread;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
@Slf4j
public class TimerThread {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Scheduled(cron = "0/5 * * * * ?")
    public void cleanExpireToken(){
        redisTemplate.convertAndSend("channel1",System.currentTimeMillis()+"");
    }
}

2、订阅

消息监听容器

package com.springboot.service;

import org.springframework.beans.factory.annotation.Qualifier;
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
public class Listener {
    /**
     * Redis消息监听容器,绑定消息监听适配器
     * @param connectionFactory
     * @param listenerAdapter 适配器1
     * @param listenerAdapter2 适配器2
     * @return
     */
    @Bean(name = "listenerContainer")
    RedisMessageListenerContainer listenerContainer(RedisConnectionFactory connectionFactory,
                                                    @Qualifier("channel1ListenerAdapter") MessageListenerAdapter listenerAdapter,
                                                    @Qualifier("channel2ListenerAdapter") MessageListenerAdapter listenerAdapter2) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //监听容器可添加多个适配器,监听多个频道
        container.addMessageListener(listenerAdapter, new PatternTopic("channel1"));
        container.addMessageListener(listenerAdapter2, new PatternTopic("channel2"));
        return container;
    }

    /**
     * 消息监听适配器,绑定消息接收器
     * @param receiver 消息接收器
     * @return
     */
    @Bean(name = "channel1ListenerAdapter")
    MessageListenerAdapter channel1ListenerAdapter(MessageReceiver receiver) {
        //利用反射技术,调用消息处理方法
        return new MessageListenerAdapter(receiver, "onMessage");
    }
    @Bean(name = "channel2ListenerAdapter")
    MessageListenerAdapter channel2ListenerAdapter(MessageReceiver receiver) {
        //利用反射技术,调用消息处理方法
        return new MessageListenerAdapter(receiver, "onMessage");
    }
}

消息接收

package com.springboot.service;

import org.springframework.stereotype.Service;

@Service
public class MessageReceiver {

    public void onMessage(String message){
        System.out.println("收到消息:"+message);
    }

}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值