我们在编写完成kakfa consumer service,将其部署到线上后有时会有启停某个topic的需求,而toipc在我们编写消费入口时就已经指定启停状态,本文提供一种热启停思路。
包含:
- 服务启动时只启动指定的topic
- 服务在线上运行时通过调用接口启停全部或指定的topic(借鉴es restful 控制)
项目使用spring boot 2.3.3.RELEASE ,spring-kafka 2.5.5.RELEASE
gradle依赖如下
ext.springbootVersion = '2.3.3.RELEASE'
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: springbootVersion
compile group: 'org.springframework.boot', name: 'spring-boot-starter-aop', version: springbootVersion
compile group: 'org.projectlombok', name: 'lombok', version: '1.16.22'
compile group: 'com.alibaba', name: 'fastjson', version: '1.2.31'
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.8.1'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator', version: '2.1.0.RELEASE'
compile group: 'org.springframework.kafka', name: 'spring-kafka', version: '2.5.5.RELEASE'
compile group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '2.1.3'
compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: springbootVersion
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.8.1'
compile group: 'com.alibaba', name: 'druid', version: '1.1.12'
compile group: 'com.alibaba', name: 'druid-spring-boot-starter', version: '1.1.10'
compile group: 'net.ipip', name: 'ipdb', version: '1.1.3'
compile group: 'org.apache.poi', name: 'poi', version: '4.1.2'
compile group: 'org.apache.poi', name: 'poi-ooxml', version: '4.1.2'
compile group: 'org.apache.poi', name: 'poi-ooxml-schemas', version: '4.1.2'
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.1.0.RELEASE'
}
kafka使用批量消费模式,批量工厂配置类如下,注意其中 factory.setAutoStartup(false);设置为不随spring自动启动
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.listener.ContainerProperties;
/**
* @Author geyunpeng
* @create 2020/9/07 17:53
* @description kafka批量工厂配置类
*/