spring.cloud.stream3.0整合rocketmq

本文简单介绍
spring cloud stream 3.x较之前版本有很大的不同,废除了@Input、@Output、@EnableBinding、@StreamListener等注解
以下内容包括生产者消费及单元测试

1、引入gradle依赖

ext {
	set('springCloudVersion', "2020.0.1")
}
dependencies {
    implementation("org.springframework.cloud:spring-cloud-stream-binder-rocketmq:0.9.0.RELEASE")
}
dependencyManagement {
	imports {
		mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
	}
}

2、配置文件

rocketmq配置及消费者配置,生产者可不配置

spring:
  cloud:
	stream:
	  rocketmq:
        binder:
          name-server: rocketmq1.com:9876;rocketmq2.com:9876
      defaultBinder: rocketmq
      binders:
        rocketmq:
          type: rocketmq
      bindings:
        handleTest-in-0:
          # 生产者发送的
          destination: test-des
          # 消费组 同一个项目中group不可重复
          group: test_group  
          # 设置spring cloud stream次数1,表示禁用,异常情况下只消费一次消息
          consumer:
            max-attempts: 1
    # 单个可不指定,多个使用`;`分号隔开
    function:
      definition: handleTest

binding命名规则
上面代码中的binding名称都是自动生成的,命名规则是:
input - <方法名> + -in- +
output - <方法名> + -out- +
Supplier为output,Consumer为input。除非方法参数有多个input或output,否则index为0。

3、生产者

@Component
@AllArgsConstructor
public class TestPublisher {

    private final StreamBridge streamBridge;

    /**
     * 发送消息
     */
    public void publish(String str) {
        streamBridge.send("test-des", str);
    }
}

4、消费者

@Component
public class TestListener {
    /**
     * 处理消息
     */
    @Bean
    public Consumer<String> handleTest() {
        return str-> {
            System.out.println(str);
        };
    }
}

5、单元测试

引入stream单元测试gradle依赖

testImplementation("org.springframework.cloud:spring-cloud-stream") {
        artifact {
            name = "spring-cloud-stream"
            extension = "jar"
            type = "test-jar"
            classifier = "test-binder"
        }
    }

如果之前添加了spring-cloud-stream-test-support依赖,需要先删除,避免冲突

@SpringBootTest
@Import({TestChannelBinderConfiguration.class}) //不会真实发送
public class RocketmqTests {

    @Resource
    private InputDestination input;
    @Resource
    private OutputDestination output;

    /** * 测试发送mq */
    @Test
    public void testInput()  {
    	//发送一条消息到交换机test-des
        input.send(MessageBuilder.withPayload("test").build(), "test-des");
        //可以立即对消息处理结果进行判断,上一步会处理完再往下运行
	 	assert ...
    }
    /** * 测试接收mq */
    @Test
    public void testOutput()  {
    	// 业务代码写在此处
    	
    	// 判断mq是否发送到交换机test-des
        Message<byte[]> outputMessage = output.receive(0, "test-des");
        assertThat(outputMessage.getPayload()).isEqualTo("test".getBytes());
    }
}

注意:若测试发送消息,本项目也是消费者,发送的消息会被项目优先消费,output.receive无法再收取消息

由于一个消费者订阅多个Topic不能使用同一个group,多个单元测试一起运行时会报错:


Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.rocketmq.spring.starter.internalRocketMQTransAnnotationProcessor' defined in class path resource [org/springframework/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.class]: Unsatisfied dependency expressed through method 'transactionAnnotationProcessor' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'transactionHandlerRegistry' defined in class path resource [org/springframework/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.class]: Unsatisfied dependency expressed through method 'transactionHandlerRegistry' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'rocketMQTemplate' defined in class path resource [org/springframework/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.class]: Invocation of init method failed; nested exception is org.apache.rocketmq.client.exception.MQClientException: The producer group[rocketmq_binder_default_group_name] has been created before, specify another name please.

在这里插入图片描述
需要添加注解@DirtiesContext 来解决:
在这里插入图片描述
@DirtiesContext :标记为污染ApplicationContext环境,运行完毕后将被移除,新的springbootTest会重新构建环境
有关此注解的可以参考:https://docs.spring.io/spring-framework/docs/5.0.8.RELEASE/spring-framework-reference/testing.html#dirtiescontext

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值