Spring Cloud 2 使用 starter-stream-kafka

梦想的初衷 提交于 2019-12-07 10:53:22


spring-cloud-starter-stream-kafka 2.X的配置很少有被讲到,但这又是springcloud架构中很重要的一块,这里做一下介绍使用,抛砖引玉。

关于新的配置项可以查询m2文件夹下的路劲:
.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.1.3.RELEASE\spring-boot-autoconfigure-2.1.3.RELEASE.jar!\META-INF\spring-configuration-metadata.json

该文件有全面的spring cloud 2配置

项目中的yml配置简单点只需要

spring:
  application:
    name: spring-producer
  kafka:
    bootstrap-servers: zhy.cauchy8389.com:9092

可以见一个service 用作sender

public interface SendService {

   @Output("myInput")
   SubscribableChannel sendOrder();
}

然后在controller里面就可以这么使用

@Autowired
SendService sendService;


@RequestMapping(value = "/send", method = RequestMethod.GET)
@ResponseBody
public String sendRequest() {
   // 创建消息
   Message msg = MessageBuilder.withPayload("Hello World".getBytes()).build();
   // 发送消息    
   sendService.sendOrder().send(msg);
   return "SUCCESS";
}

至于linux中kafka的启动命令:

kafka-topics.sh --create --zookeeper zhy.cauchy8389.com:2181/kafka --replication-factor 1 --partitions 2 --topic myInput 

这里解释下partitions 里面的数字就是届时分发的次数,也就是consumer接收的次数(一个consumer groupid接受的次数)

见一个consumer:

@SpringBootApplication
@EnableBinding(value = {ReceiveService.class})
public class ReceiverApplication {
   
   public static void main(String[] args) {
      new SpringApplicationBuilder(ReceiverApplication.class).
            properties("spring.config.location=classpath:/springcloud/stream-consumer.yml").run(args);
   }

   @StreamListener("myInput")
   public void receive(byte[] msg) {
      System.out.println("接收到的消息:  " + new String(msg));
   }
   
}

配置yml文件里面配上:

spring:
  application:
    name: spring-consumer
  kafka:
        bootstrap-servers: zhy.cauchy8389.com:9092
        consumer:
          group-id: group1

可以建立多个consumer project 也可以用同一个group-id ,然后之前partitions配置为2 那也就是比如这个group1 我启动多个

那么只有2个group1的实例会接收到队列消息。

好了,有什么问题,请留言咨询

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!