Kafka及Spring Cloud Stream
安装
下载kafka http://mirrors.hust.edu.cn/apache/kafka/2.0.0/kafka_2.11-2.0.0.tgz
kafka最为重要三个配置依次为:broker.id、log.dir、zookeeper.connect
在kafka server端 config/server.properties中设置
必须要配置:
advertised.listeners=PLAINTEXT://192.168.3.201:9092 # 公布访问地址和端口
启动kafka
bin/kafka-server-start.sh ../config/server.properties
检测是否启动
netstat -tunlp | egrep " (2181|9092)"
或 lsof -i:9092
测试发送信息和消费消息
创建主题
./kafka-topics.sh --create --zookeeper localhost:2182 --replication-factor 1 --partitions 1 - topic test
生产者
./kafka-console-producer.sh --broker-list localhost:9092 --topic test
消费者
./kafkaconsole-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning
如果想在外部使用kafka必须 9092 端口加入到防火墙列表
firewall-cmd --list-ports 查询所有放行端口
firewall-cmd --add-port=9092/tcp # 临时端口放行
firewall-cmd --add-port=9092/tcp --permanent # 永久放行
firewall-cmd --reload # 重新载入放行列表
简单API的应用
引入依赖
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
编写生成者
package com.example.springkafka.api; import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer; import java.util.Properties; /**
* @Date: 2018/11/6 20:25
* @Description: 生产者
*/
public class KafkaProducerDemo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("bootstrap.servers","192.168.3.221:9092");
properties.setProperty("key.serializer", StringSerializer.class.getName());
properties.setProperty("value.serializer", StringSerializer.class.getName());
KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(properties);
String topic = "message"; // 主题
Integer partition = 0; // 指定分区
long timeMillis = System.currentTimeMillis(); // 毫秒值 15分钟
String key = "key-message"; // key
String value = "value-message"; // value
// 创建ProducerRecord
ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>(topic, partition, timeMillis, key, value);
// 生产消息
kafkaProducer.send(producerRecord);
kafkaProducer.close();
}
}
编写消费者
package com.example.springkafka.api; import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer; import java.util.Arrays;
import java.util.Properties; /**
* @Date: 2018/11/6 20:25
* @Description: 消费者
*/
public class KafkaConsumerDemo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("bootstrap.servers", "192.168.3.221:9092");
properties.setProperty("group.id", "group-1");
properties.setProperty("key.deserializer", StringDeserializer.class.getName());
properties.setProperty("value.deserializer", StringDeserializer.class.getName());
// 创建kafka的消费者对象
KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(properties);
// 订阅kafka主题
kafkaConsumer.subscribe(Arrays.asList("message"));
while (true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(1000);
for (ConsumerRecord<String, String> record : records)
System.out.printf("========offset = %d, key = %s, value = %s\n", record.offset(), record.key(), record.value());
}
}
}
spring kafka
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-kafka</artifactId>
</dependency>
生成者与消费者配置
# 生成者配置
spring:
kafka:
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringSerializer
bootstrap-servers: 192.168.3.221:9092
consumer: # 消费者
group-id: gerry-1
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
kafka:
topic: gerry
生成者代码
package com.example.springcloudkafka.controller; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; /**
* @Date: 2018/11/6 21:03
* @Description:
*/
@RestController
public class KafkaProducerController {
public final KafkaTemplate<String, String> kafkaTemplate;
private final String topic; public KafkaProducerController(KafkaTemplate<String, String> kafkaTemplate,
@Value("${kafka.topic}") String topic) {
this.kafkaTemplate = kafkaTemplate;
this.topic = topic;
} @PostMapping("message/send") // 这种方式只支持post
public boolean sendMessage(@RequestParam String message) {
kafkaTemplate.send(topic,message); return true;
}
}
消费者代码
package com.example.springcloudkafka.listener; import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component; /**
* @Date: 2018/11/6 21:20
* @Description:
*/
@Component
public class KafkaConsumerListener { @KafkaListener(topics={"${kafka.topic}"})
public void getMessage(String message) {
System.out.println("kafka 消费者监听,接收到消息:" + message);
}
}
Spring Cloud Stream
官方定义三个接口
Source=> 发送者 Producer、Publisher
Sink=> 接收器 Consumer、 Subscriber Processor: 上流而言Sink、下流而言Souce
Spring Cloud Stream Binder: Kafka
引入依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-kafka</artifactId>
</dependency>
配置:
# 生成者配置
spring:
kafka:
bootstrap-servers: 192.168.3.221:9092
cloud:
stream:
bindings:
output:
destination: ${kafka.topic}
input:
destination: ${kafka.topic}
kafka:
topic: cloud-stream
生产者:
package com.example.springcloudstreamkafkademo.producer; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component; @Component
@EnableBinding(Source.class)
public class MessageProducerBean {
@Autowired
@Qualifier(Source.OUTPUT)
private MessageChannel messageChannel; @Autowired
private Source source; /**
* 发送信息
* @param message
*/
public void send(String message) {
// 通过消息管道发送消息
// messageChannel.send(MessageBuilder.withPayload(message).build());
source.output().send(MessageBuilder.withPayload(message).build());
}
}
消费者
package com.example.springcloudstreamkafkademo.consumer; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Component
@EnableBinding(value={Sink.class})
public class MessageConsumerBean {
@Autowired
@Qualifier(Sink.INPUT)
private SubscribableChannel subscribableChannel; //1、 当subscribableChannel注入完成后完成回调
@PostConstruct
public void init() {
subscribableChannel.subscribe(message->{
System.out.println(message.getPayload());
});
}
// 2、@ServiceActivator
@ServiceActivator(inputChannel=Sink.INPUT)
public void message(String message) {
System.out.println("@ServiceActivator:"+message);
}
//3、@StreamListener
@StreamListener(Sink.INPUT)
public void onMessage(String message) {
System.out.println("@StreamListener:"+message);
}
}
Spring Cloud Stream Binder: RabbitMQ
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
配置
spring:
cloud:
stream:
bindings:
output:
destination: ${rabbit.queue}
input:
destination: ${rabbit.queue}
rabbitmq:
host: 192.168.3.221
port: 5672
username: rabbit
password: rabbit
rabbit:
queue: cloud-stream-queue
代码同kafka
完整代码详见:https://gitee.com/lm970585581/cloud-config/tree/master/Spring%20Cloud%20Stream%20
Kafka及Spring Cloud Stream的更多相关文章
- SpringCloud微服务实战——搭建企业级开发框架(三十六):使用Spring Cloud Stream实现可灵活配置消息中间件的功能
在以往消息队列的使用中,我们通常使用集成消息中间件开源包来实现对应功能,而消息中间件的实现又有多种,比如目前比较主流的ActiveMQ.RocketMQ.RabbitMQ.Kafka,Stream ...
- 这事没完,继续聊spring cloud stream和kafka的这些小事
上一篇文章讲了如何用spring cloud stream集成kafka,并且跑起来一个demo,如果这一次宣传spring cloud stream的文章,其实到这里就可以啦.但实际上,工程永远不是 ...
- 简单聊一聊spring cloud stream和kafka的那点事
Spring Cloud Stream is a framework for building highly scalable event-driven microservices connected ...
- Spring Cloud Stream如何处理消息重复消费?
最近收到好几个类似的问题:使用Spring Cloud Stream操作RabbitMQ或Kafka的时候,出现消息重复消费的问题.通过沟通与排查下来主要还是用户对消费组的认识不够.其实,在之前的博文 ...
- 使用 Spring Cloud Stream 构建消息驱动微服务
相关源码: spring cloud demo 微服务的目的: 松耦合 事件驱动的优势:高度解耦 Spring Cloud Stream 的几个概念 Spring Cloud Stream is a ...
- 第十章 消息驱动的微服务: Spring Cloud Stream
Spring Cloud Stream 是一个用来为微服务应用构建消息驱动能力的框架. 它可以基于Spring Boot 来创建独立的. 可用于生产的 Spring 应用程序. 它通过使用 Sprin ...
- Spring cloud stream【入门介绍】
案例代码:https://github.com/q279583842q/springcloud-e-book 在实际开发过程中,服务与服务之间通信经常会使用到消息中间件,而以往使用了哪个中间件比如 ...
- 消息驱动式微服务:Spring Cloud Stream & RabbitMQ
1. 概述 在本文中,我们将向您介绍Spring Cloud Stream,这是一个用于构建消息驱动的微服务应用程序的框架,这些应用程序由一个常见的消息传递代理(如RabbitMQ.Apache Ka ...
- spring cloud stream 经验总结
---恢复内容开始--- 基本概念 spring: cloud: stream: kafka: binder: brokers: cloudTest:19092 zk-nodes: cloudTest ...
随机推荐
- 20155307 2016-2017-2 《Java程序设计》第10周学习总结
20155307 2016-2017-2 <Java程序设计>第10周学习总结 教材学习内容总结 网络编程:就是在两个或两个以上的设备(例如计算机)之间传输数据.程序员所作的事情就是把数据 ...
- 20155323 2016-2017-2 《Java程序设计》第10周学习总结
20155323 2016-2017-2 <Java程序设计>第10周学习总结 教材学习内容总结 网络编程就是在两个或两个以上的设备(例如计算机)之间传输数据. 狭义的网络编程范畴就是程序 ...
- 20145207《Java程序设计》实验二(Java面向对象程序设计)实验报告
<Java程序设计>实验二(Java面向对象程序设计)实验报告 目录 改变 Java面向对象程序设计实验要求 实验成果 课后思考 改变 看了下之前实验二的整体,很搞笑,大图+代码,没了.. ...
- 每天一个linux命令(1):ln 命令
每天一个linux命令(35):ln 命令 ln 是linux中又一个非常重要命令,它的功能是为某一个文件在另外一个位置建立一个同步的链接.当我们需要在不同的目录,用到相同的文件时,我们不需要在 每一 ...
- python3.0 day02 列表、元组 、字典、字符串操作
1.列表.元组操作 列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储.修改等操作,类似于其他语言中的数组. 定义列表 names = ['Lioa',"Tenglan ...
- docker制作自己的镜像并上传dockerhub
1.首先注册自己的dockerhub账号,注册地址:https://hub.docker.com 2.在linux服务器登录自己的账号:docker login --username=qiaoyeye ...
- JS基础,课堂作业,相亲问答
相亲问答 <script> var a = prompt("你有房子么?"); var b = prompt("你有钱么?"); var c = p ...
- linux系统CPU内存磁盘监控发送邮件脚本
#!/bin/bashexport PATHexport LANG=zh_CN.UTF-8###top之后输入数字1,可以查看每颗CPU的情况.###先配置好mailx邮箱账号密码:#cat>/ ...
- https双向认证网站搭建
新建网站 在搭建网站证书之前,我们先搭建好我们的网站 1.网站基本搭建 为我们的项目新建一个网站,按照如下的步骤来 1,打开IIS,右键单击网站弹出菜单,选择网站(如图1.1.1) 图1.1.1 2, ...
- JSP整理
JSP全称Java Server Pages,是一种动态网页开发技术.它使用JSP标签在HTML网页中插入Java代码.标签通常以<%开头以%>结束. JSP是一种Java servlet ...