1、依赖

1
2
3
4
<dependency>
          <groupId>com.alibaba.cloud</groupId>
          <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
      </dependency>

 2、配置

1
2
3
4
5
6
7
8
9
10
11
12
13
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();
    }
复制代码