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 ...
随机推荐
- 20155231 2016-2017-2 《Java程序设计》第10周学习总结
20155231 2016-2017-2 <Java程序设计>第10周学习总结 教材学习内容总结 学习目标 了解计算机网络基础 掌握Java Socket编程 理解混合密码系统 掌握Jav ...
- hive bug
SHELL$ hive -S -e “set” | grep warehouse hive.metastore.warehouse.dir=/user/hive/warehouse hive.ware ...
- unity游戏在ios11上不显示泰语解决办法
最近在开发中遇到unity游戏在ios11上不显示泰语的问题,全部显示为方框内一个问号. 通过搜索发现这是Unity的一个bug,在2017.3中修复了 但升级unity风险很大,所以我采用了该文中提 ...
- 我想这次我真的理解了 JavaScript 的单线程机制
今天面试的时候被问到一个问题,是关于 JS 异步的.当时我脑海中闪过了一个单线程的概念,但却没有把真正的原理阐述清楚.所以回来特意重新回顾了前面单线程和异步相关的一些知识点. 虽然之前学习的时候也接触 ...
- rz和sz上传下载文件
安装软件包 yum install lrzsz 上传文件,输入rz选择文件上传(可以按住shift键多选) # rz sz 下载文件到本地,选择保存文件夹 # sz dd xshell设 ...
- day04 list tuple (补)
今日内容: 1. 列表 2. 列表的增删改查 3. 列表的嵌套 4. 元组和元组嵌套 5. range 列表 列表: 能装对象的对象. 有顺序的(按照我们添加的顺序保存) 在代码中使用[]表示列表. ...
- leetcode28_C++实现strStr()函数
实现 strStr() 函数. 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始).如果不存在,则返 ...
- 算法笔记(c++)--01背包问题
算法笔记(c++)--经典01背包问题 算法解释起来太抽象了.也不是很好理解,最好的办法就是一步步写出来. 背包问题的核心在于m[i][j]=max(m[i-1][j],m[i-1][j-w[i]]+ ...
- POWERDESIGNER生成的代码有引号
昨天在用powerdesigner画的一个导入ORACLE中.发现都带了双引号, 当时没在意,以为是分隔符.那想后要在ORACLE查询表是一定要输入双引号才能查询.. 后来才知道而这在oracle 中 ...
- Linux下的计算器(bc、expr、dc、echo、awk)知多少?
linux 其他知识目录 原文链接:http://blog.chinaunix.net/uid-24673811-id-1760837.html linux下的三个命令可以用来作计算,下面一一讲解用法 ...