Redis 发布订阅MessageListener

config 配置

package com.app.common.redis.config;

import com.app.common.redis.enums.RedisPubSubTopicEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.MessageListener;
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;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

/**
 * 动态创建redis sub 监听器,
 * 根据SPI 机制实现自动装配
 * 通过spring上下文获取RedisConnectionFactory redis连接工厂
 *
 * @author lilincheng
 * @date 2023/4/14 下午4:32
 */
@Slf4j
@Component
public class RedisSubConfig implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    /**
     * 动态创建消息监听容器
     *
     * @return {@link RedisMessageListenerContainer}
     */
    @Bean
    public RedisMessageListenerContainer getRedisMessageListenerContainer(Executor executor) {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        //通过spring上下文获取RedisConnectionFactory redis连接工厂
        applicationContext.getBeansOfType(RedisConnectionFactory.class).values().forEach(redisMessageListenerContainer::setConnectionFactory);
        redisMessageListenerContainer.setTaskExecutor(executor);

        //根据SPI 机制实现自动装配
        for (MessageListener component : applicationContext.getBeansOfType(MessageListener.class).values()) {
            List<PatternTopic> patternTopicList = Arrays.stream(RedisPubSubTopicEnum.values()).map(x -> new PatternTopic(x.name())).collect(Collectors.toList());
            redisMessageListenerContainer.addMessageListener(new MessageListenerAdapter(component), patternTopicList);
        }

        return redisMessageListenerContainer;
    }


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

enums

package com.app.common.redis.enums;

/**
 * redis 订阅topic名称枚举
 * @author lilincheng
 * @date 2023/4/14 下午3:59
 */
public enum  RedisPubSubTopicEnum {

    /**
     * topic 聊天完成请求
     */
    CHAT_COMPLETIONS_PARAM_TOPIC,

    /**
     * topic 聊天完成结果
     */
    CHAT_COMPLETIONS_RESULT_TOPIC,
    ;
}

receiver

抽象消息处理器

package com.app.common.redis.receiver;

import org.springframework.data.redis.connection.Message;

/**
 * 抽象消息处理器
 * @author lilincheng
 * @date 2023/4/24 下午6:28
 */
public abstract class RedisAbstractMsgProcessor {

    /**
     * 获取topic Name 话题名称
     *
     * @return 话题名称
     */
    public abstract String getTopicName();

    /**
     * 处理消息
     */
    public abstract void execute(Message message, byte[] bytes);

}

监听上下文管理器

package com.app.common.redis.receiver;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * redis 监听管理器
 *
 * @author lilincheng
 * @date 2023/4/24 下午6:24
 */
@Slf4j
@Component
public class RedisReceiverContextListener implements MessageListener {

    @Autowired
    private ApplicationContext applicationContext;

    private Map<String, RedisAbstractMsgProcessor> processorMap;

    @Autowired
    public void setProcessorMap() {
        //注入所有指令处理类
        this.processorMap = applicationContext.getBeansOfType(RedisAbstractMsgProcessor.class).values().stream().collect(Collectors.toMap(RedisAbstractMsgProcessor::getTopicName, filterAlgorithm -> filterAlgorithm));
    }


    @Override
    public void onMessage(Message message, byte[] bytes) {
        RedisAbstractMsgProcessor processor = processorMap.get(new String(message.getChannel()));
        if (Objects.isNull(processor)) {
            log.info("找不到指定命令");
            return;
        }
        processor.execute(message, bytes);

        log.info("订阅消息,订阅名称:{},{}", new String(message.getChannel()), message);
    }
}

Processor (分布式,微服务中的数据处理,每个微服务可能存在监听不一样的topic)

package com.app.service.module.ai.redis;

import com.alibaba.fastjson.JSON;
import com.app.common.gpt.dto.ChatCompletionResult;
import com.app.common.gpt.service.OpenAIAPIService;
import com.app.common.redis.enums.RedisPubSubTopicEnum;
import com.app.common.redis.receiver.RedisAbstractMsgProcessor;
import com.app.common.redis.util.RedisTools;
import com.app.service.bridge.dto.chat.ChatDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * chat 请求
 *
 * @author lilincheng
 * @date 2023/4/26 上午11:37
 */
@Slf4j
@Component
public class RedisChatParamProcessor extends RedisAbstractMsgProcessor {
    @Autowired
    private RedisTools redisTools;

    @Autowired
    private OpenAIAPIService openAIAPIService;

    @Override
    public String getTopicName() {
        return RedisPubSubTopicEnum.CHAT_COMPLETIONS_PARAM_TOPIC.name();
    }


    @Override
    public void execute(Message message, byte[] bytes) {
        log.info("收到的redis chat 请求 订阅消息:{}", message.toString());
        ChatDTO dto = JSON.parseObject(message.toString(), ChatDTO.class);
        dto.setTargetType(2);
        dto.setText("当前人数访问较多,请稍后再试~");

        if (dto.getCheckStatus() == 3 && dto.getPlatform() == 1) {
            dto.setText(dto.getSendMessage());
            redisTools.sendMsg(RedisPubSubTopicEnum.CHAT_COMPLETIONS_RESULT_TOPIC, JSON.toJSONString(dto));
            return;
        }

        //3、请求第三方Chat GPT 对话、处理返回Chat GPT对话信息
        log.info("【ChatRecordServiceImpl.executeBuildChatCompletion】- 聊天开始请求第三方GPT Chat 。  请求参数:{}", dto);
        ChatCompletionResult completionResult = openAIAPIService.chatCompletions(dto.getAiKey(), dto.getUserId().toString(), dto.getSendMessage());
        log.info("【ChatRecordServiceImpl.executeBuildChatCompletion】- 聊天结束完成请求返回结果:{}", completionResult);
        if (Objects.nonNull(completionResult) && Objects.nonNull(completionResult.getChoices()) && !completionResult.getChoices().isEmpty()) {
            dto.setText(completionResult.getChoices().get(0).getMessage().getContent());
            redisTools.sendMsg(RedisPubSubTopicEnum.CHAT_COMPLETIONS_RESULT_TOPIC, JSON.toJSONString(dto));
            return;
        }
        redisTools.sendMsg(RedisPubSubTopicEnum.CHAT_COMPLETIONS_RESULT_TOPIC, JSON.toJSONString(dto));
    }

}

关注博主动态

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

乔-治

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

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

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

打赏作者

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

抵扣说明:

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

余额充值