美文网首页
springboot redis 实现发布订阅模式

springboot redis 实现发布订阅模式

作者: 小黄龙V5 | 来源:发表于2020-04-11 20:58 被阅读0次

引入maven包

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

redis链接配置

spring:
  redis:
    host: localhost
    port: 6379
    password: redis
    database: 1
    pool:
      max-active: 100
      max-idle: 10
      max-wait: 100000
    timeout: 1000

reidis 配置

@Configuration
public class RedisConfig {
    @Autowired
    RedisConnectionFactory redisConnectionFactory;
    /**
     * 实例化 RedisTemplate 对象
     *
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> functionDomainRedisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
        return redisTemplate;
    }

    /**
     * 设置数据存入 redis 的序列化方式,并开启事务
     *
     * @param redisTemplate
     * @param factory
     */
    private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
        //如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 开启事务
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.setConnectionFactory(factory);
    }

    /**
     * 注入封装RedisTemplate
     *
     * @return RedisUtil
     * @throws
     * @Title: redisUtil
     * @date 2017年12月21日
     */
    @Bean(name = "redisUtil")
    public RedisUtils redisUtil(RedisTemplate<String, Object> redisTemplate) {
        RedisUtils redisUtil = new RedisUtils();
        redisUtil.setRedisTemplate(redisTemplate);
        return redisUtil;
    }
}

简单封装redis 调用方法


import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit;

public class RedisUtils {

    private RedisTemplate<String, Object> redisTemplate;

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    //=============================common============================  

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 发布
     *
     * @param topic
     * @param message
     */
    public void publish(String topic, Object message) {
        try {
            redisTemplate.convertAndSend(topic, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

发送一个demo

@Component
@Slf4j
public class SyncProject {
    @Resource
    RedisUtils redisUtils;
    
    public void demo() {
        redisUtils.publish("redis-publish-topic", "1");
    }
}

监听消息 处理

@Service
@Slf4j
public class SyncDemo implements MessageListener {
    
    @Override
    public void onMessage(Message message, byte[] bytes) {
        String name = this.getClass().getSimpleName();
        log.info("接受处理 name{}", name);
        String topic = new String(message.getChannel());
        log.info("接受处理 topic{}", topic);
        String content = new String(message.getBody());
        log.info("接受处理 content{}", content);
    }

注册消息监听

@Configuration
@Slf4j
public class SubscriberConfig {
    @Autowired
    RedisConnectionFactory redisConnectionFactory;


    @Autowired
    SyncDemo syncDemo;
    @Bean
    ChannelTopic topicProject() {
        return new ChannelTopic("redis-publish-topic");
    }
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer() {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        container.addMessageListener(syncDemo, topicProject());
        return container;
    }
}

到此完成了redis发布与订阅。

相关文章

网友评论

      本文标题:springboot redis 实现发布订阅模式

      本文链接:https://www.haomeiwen.com/subject/aedpmhtx.html