SpringBoot Redis 实现消息发布与订阅

本文介绍如何在Spring Boot项目中引入Redis,并配置RedisTemplate进行序列化操作,实现消息发布与订阅功能。

1、POM 引入

<parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.2.4.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
</parent>

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

2、Redis配置

spring:
  redis:
    host: ${ip.redis}
    port: 6379
    database: 0

3、RedisTemplate配置,Redis消息事件注册

package com.cict.iwu.project.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
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.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.*;

@Configuration
public class RedisTemplateConfig implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        // 设置redis连接
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 设置value的序列化规则和 key的序列化规则
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // 将redisTemplate的序列化方式更改为StringRedisSerializer
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }



    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(applicationContext.getBean(LoggerEventListener.class),new ChannelTopic(Constants.CHANNEL_LOGGER));
        return container;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RedisTemplateConfig.applicationContext = applicationContext;
    }
}

4、Redis消息发布

    @Override
    public void addAuditLog(AuditLog auditLog) {
        if (auditLog != null) {
            IWULog iwulog = (IWULog) auditLog;
            iwulog.setLogContent(logContentDecrypt(iwulog));
            redisUtils.publish(Constants.CHANNEL_LOGGER, iwulog.toString());
            log.debug("============================================="+JSONObject.toJSONString(iwulog));
        }
    }

5、Redis消息消费

package com.cict.iwu.project.config;


import com.cict.iwu.project.uitl.EnvUtils;
import com.cict.iwu.project.uitl.FileWriteUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Slf4j
@Component
@DependsOn("envUtils")
public class LoggerEventListener extends MessageListenerAdapter {


    public LoggerEventListener() {
        super();
        // first:检查日志文件目录是否存在,不存在则创建
        checkParentFolder();
        //second:加载并检查日志文件是否存在,不存在则创建
        load();
    }

    @Override
    public void onMessage(Message message, @Nullable byte[] pattern) {
        logger.debug("***************************************************{}" + new String(message.getBody()));
        //日志文件每天动态生成。
        load();
        FileWriteUtils.writeNewLineAppend(writer, new String(message.getBody()), true);
    }

    /**
     * 检查日志文件是否存在,不存在则创建日志文件;检查日志文件writer是否创建,没有则创建日志文件Writer
     */
    private void load() {
    
    }


}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

仰望星空@脚踏实地

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值