惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
月光博客
月光博客
S
SegmentFault 最新的问题
有赞技术团队
有赞技术团队
Stack Overflow Blog
Stack Overflow Blog
Engineering at Meta
Engineering at Meta
T
The Blog of Author Tim Ferriss
The GitHub Blog
The GitHub Blog
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
IT之家
IT之家
宝玉的分享
宝玉的分享
A
About on SuperTechFans
Vercel News
Vercel News
P
Proofpoint News Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 【当耐特】
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
Jina AI
Jina AI
Y
Y Combinator Blog
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Last Week in AI
Last Week in AI

博客园 - 蜗牛无敌

管理心得-协调 项目git 提交 hooks excel 公式支持 ~ - flowable-ui本地部署 mqtt实战 自动生成提示 修改表中数据时候,关联查询,例如删除一张表中 小于最大时间的sql, rocketmq-spring-boot-starter的使用 MYSQL ORDER BY 自定义排序 java程序cpu飘高排查 window canal的本地部署 是用hutool工具实现动态定时任务 python使用selenium框架模拟登录 获取token,并打包成exe spring-cloud-stater-stream-rocketmq springboot mybatisplus 使用拦截器改写sql语句 spring-cloud-stream-rocketmq实现消息的顺序消息 springboot 集成es 使用resthightlevel springboot 多租户环境下 由于业务需要搜集所有租户的基本数据 springboot为基础的项目 由于线上日志打印的级别较低,无法打印日志的方法 window系统关闭指定端口的应用方法
spring boot rockmq 生产者和消费者 实战
蜗牛无敌 · 2025-03-06 · via 博客园 - 蜗牛无敌

1、依赖

  <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
        </dependency>

 2、配置

spring:
  cloud:
    stream:
      rocketmq:
        binder:
          name-server: 139.155.157.74:30094  # RocketMQ NameServer地址
      bindings:
        helpAiLogOutput:
          destination: help-ai-log-topic  # 生产者的Topic
          group: help-ai-log-group-product  # 生产者的Group
        helpAiLogInput:
          destination: help-ai-log-topic  # 消费者的Topic
          group: help-ai-log-group-consumer  # 消费者的Group

 3、定义生产

import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;

public interface HelpAiLogSource {
    String HELP_AI_LOG_OUTPUT = "helpAiLogOutput";

    @Output(HELP_AI_LOG_OUTPUT)
    MessageChannel helpAiLogOutput();
}
import jnpf.helpailog.config.HelpAiLogSource;
import jnpf.model.helpailog.po.FtbHelpAiChatLog;
import org.apache.rocketmq.common.message.MessageConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Service
@EnableBinding(HelpAiLogSource.class)
public class HelpAiLogProducer {

    @Autowired
    private HelpAiLogSource helpAiLogSource;

    public void sendMessage(FtbHelpAiChatLog dto) {
        //怎么给消息打上tag

        helpAiLogSource.helpAiLogOutput().send(MessageBuilder.withPayload(dto).setHeader(MessageConst.PROPERTY_TAGS, dto.getTenantId() + "_" + dto.getUserId()).setHeader(MessageConst.PROPERTY_KEYS, dto.getSessionId()).build());
    }
}

4、定义消费

import org.springframework.cloud.stream.annotation.Input;
import org.springframework.messaging.SubscribableChannel;

public interface HelpAiLogSink {
    String HELP_AI_LOG_INPUT = "helpAiLogInput";

    @Input(HELP_AI_LOG_INPUT)
    SubscribableChannel helpAiLogInput();
}
import cn.hutool.json.JSONUtil;
import jnpf.base.UserInfo;
import jnpf.config.ConfigValueUtil;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.LoginException;
import jnpf.helpailog.config.HelpAiLogSink;
import jnpf.helpailog.service.FtbHelpAiChatLogService;
import jnpf.model.helpailog.po.FtbHelpAiChatLog;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import jnpf.util.data.DataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Service
@Slf4j
@EnableBinding(HelpAiLogSink.class)
public class HelpAiLogConsumer {

    @Autowired
    private FtbHelpAiChatLogService ftbHelpAiChatLogService;

    @Autowired
    private ConfigValueUtil configValueUtil;

    @StreamListener(HelpAiLogSink.HELP_AI_LOG_INPUT)
    public void receive(String message) {
        FtbHelpAiChatLog entity = JSONUtil.toBean(message, FtbHelpAiChatLog.class);
        log.info("0000000接收到消息:{}", message);
        switchTenant(entity.getTenantId());
        ftbHelpAiChatLogService.record(entity);
    }

    private void switchTenant(String tenantId) {
        // 判断是否为多租户
        if (configValueUtil.isMultiTenancy()) {
            // 判断是不是从外面直接请求
            if (StringUtil.isNotEmpty(tenantId)) {
                //切换成租户库
                try {
                    TenantDataSourceUtil.switchTenant(tenantId);
                } catch (LoginException e) {
                    throw new RuntimeException("切换租户失败");
                }
            } else {
                UserInfo userInfo = UserProvider.getUser();
                Assert.notNull(userInfo.getUserId(), "缺少租户信息");
                DataSourceContextHolder.setDatasource(userInfo.getTenantId(), userInfo.getTenantDbConnectionString(), userInfo.isAssignDataSource());
            }
        }
    }
}

5、定义测试接口

    @Autowired
    private HelpAiLogProducer helpAiLogProducer;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private FtbHelpAiChatLogService ftbHelpAiChatLogService;

    /**
     * @param dto
     * @return
     */
    @PostMapping("/record")
    public ActionResult<Boolean> record(@Validated @RequestBody HelpAiLogDto dto) {

        try {
            UserInfo userInfo = userProvider.get();
            String userId = userInfo.getUserId();
            String tenantId = userInfo.getTenantId();
            helpAiLogProducer.sendMessage(dto.convertToEntity(userId, tenantId));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("帮助ai 聊天记录异常:{},{}", dto, e);
        }
        return ActionResult.success();
    }