SSM(十七) MQ应用_kafka

前言

写这篇文章的起因是由于之前的一篇关于 ​Kafka​​​异常消费​​,当时为了解决问题不得不使用临时的方案。

总结起来归根结底还是对Kafka不熟悉导致的,加上平时工作的需要,之后就花些时间看了 ​Kafka​相关的资料。

何时使用MQ

谈到 ​Kafka​就不得不提到MQ,是属于消息队列的一种。作为一种基础中间件在互联网项目中有着大量的使用。

一种技术的产生自然是为了解决某种需求,通常来说是以下场景:

  • 需要跨进程通信:B系统需要A系统的输出作为输入参数。
  • 当A系统的输出能力远远大于B系统的处理能力。

针对于第一种情况有两种方案:

  • 使用 ​RPC​远程调用,A直接调用B。
  • 使用 ​MQ​​,A发布消息到 ​​MQ​​,B订阅该消息。

当我们的需求是:A调用B实时响应,并且实时关心响应结果则使用 ​RPC​,这种情况就得使用同步调用。

反之当我们并不关心调用之后的执行结果,并且有可能被调用方的执行非常耗时,这种情况就非常适合用 ​MQ​来达到异步调用目的。

比如常见的登录场景就只能用同步调用的方式,因为这个过程需要实时的响应结果,总不能在用户点了登录之后排除网络原因之外再额外的等几秒吧。

但类似于用户登录需要奖励积分的情况则使用 ​MQ​​会更好,因为登录并不关系积分的情况,只需要发个消息到 ​MQ​,处理积分的服务订阅处理即可,这样还可以解决积分系统故障带来的雪崩效应。

MQ​还有一个基础功能则是限流削峰,这对于大流量的场景如果将请求直接调用到B系统则非常有可能使B系统出现不可用的情况。这种场景就非常适合将请求放入 ​MQ​​,不但可以利用 ​MQ​削峰还尽可能的保证系统的高可用。

Kafka简介

本次重点讨论下 ​Kafka​​。 简单来说 ​​Kafka​是一个支持水平扩展,高吞吐率的分布式消息系统。

Kafka​的常用知识:

  • ​Topic​​​:生产者和消费者的交互都是围绕着一个 ​​Topic​​进行的,通常来说是由业务来进行区分,由生产消费者协商之后进行创建。
  • ​Partition​​​(分区):是 ​​Topic​​下的组成,通常一个 ​​Topic​​下有一个或多个分区,消息生产之后会按照一定的算法负载到每个分区,所以分区也是 ​​Kafka​​性能的关键。当发现性能不高时便可考虑新增分区。

结构图如下:

SSM(十七) MQ应用_kafka_02

创建 Topic

Kafka​​的安装官网有非常详细的讲解。这里谈一下在日常开发中常见的一些操作,比如创建 ​Topic​:

  1. sh bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 3 --topic `test`

创建了三个分区的 ​test​主题。

使用

  1. sh bin/kafka-topics.sh --list --zookeeper localhost:2181

可以列出所有的 ​Topic​。

Kafka生产者

使用 ​kafka​​官方所提供的 ​JavaAPI​来进行消息生产,实际使用中编码实现更为常用:

  1. /** Kafka生产者
  2. * @author crossoverJie
  3. */
  4. public class Producer {
  5.    private static final Logger LOGGER = LoggerFactory.getLogger(Producer.class);

  6.    /**
  7.     * 消费配置文件
  8.     */
  9.    private static String consumerProPath;

  10.    public static void main(String[] args) throws IOException {
  11.        // set up the producer
  12.        consumerProPath = System.getProperty("product_path");
  13.        KafkaProducer<String, String> producer = null;
  14.        try {
  15.            FileInputStream inputStream = new FileInputStream(new File(consumerProPath));
  16.            Properties properties = new Properties();
  17.            properties.load(inputStream);
  18.            producer = new KafkaProducer<String, String>(properties);

  19.        } catch (IOException e) {
  20.            LOGGER.error("load config error", e);
  21.        }

  22.        try {
  23.            // send lots of messages
  24.            for (int i=0 ;i<100 ; i++){
  25.                producer.send(new ProducerRecord<String, String>(
  26.                        "topic_optimization", i+"", i+""));

  27.            }
  28.        } catch (Throwable throwable) {
  29.            System.out.printf("%s", throwable.getStackTrace());
  30.        } finally {
  31.            producer.close();
  32.        }

  33.    }
  34. }

再配合以下启动参数即可发送消息:

  1. -Dproduct_path=/xxx/producer.properties

以及生产者的配置文件:

  1. #集群地址,可以多个
  2. bootstrap.servers=10.19.13.51:9094
  3. acks=all
  4. retries=0
  5. batch.size=16384
  6. auto.commit.interval.ms=1000
  7. linger.ms=0
  8. key.serializer=org.apache.kafka.common.serialization.StringSerializer
  9. value.serializer=org.apache.kafka.common.serialization.StringSerializer
  10. block.on.buffer.full=true

具体的配置说明详见此处:https://kafka.apache.org/0100/documentation.html#theproducer

流程非常简单,其实就是一些 ​API​的调用。

消息发完之后可以通过以下命令查看队列内的情况:

  1. sh kafka-consumer-groups.sh --bootstrap-server localhost:9094 --describe --group group1

SSM(十七) MQ应用_apache_03

其中的 ​lag​便是队列里的消息数量。

Kafka消费者

有了生产者自然也少不了消费者,这里首先针对单线程消费:

  1. /**
  2. * Function:kafka官方消费
  3. *
  4. * @author crossoverJie
  5. *         Date: 2017/10/19 01:11
  6. * @since JDK 1.8
  7. */
  8. public class KafkaOfficialConsumer {
  9.    private static final Logger LOGGER = LoggerFactory.getLogger(KafkaOfficialConsumer.class);

  10.    /**
  11.     * 日志文件地址
  12.     */
  13.    private static String logPath;

  14.    /**
  15.     * 主题名称
  16.     */
  17.    private static String topic;

  18.    /**
  19.     * 消费配置文件
  20.     */
  21.    private static String consumerProPath ;


  22.    /**
  23.     * 初始化参数校验
  24.     * @return
  25.     */
  26.    private static boolean initCheck() {
  27.        topic = System.getProperty("topic") ;
  28.        logPath = System.getProperty("log_path") ;
  29.        consumerProPath = System.getProperty("consumer_pro_path") ;
  30.        if (StringUtil.isEmpty(topic) || logPath.isEmpty()) {
  31.            LOGGER.error("system property topic ,consumer_pro_path, log_path is required !");
  32.            return true;
  33.        }
  34.        return false;
  35.    }

  36.    /**
  37.     * 初始化kafka配置
  38.     * @return
  39.     */
  40.    private static KafkaConsumer<String, String> initKafkaConsumer() {
  41.        KafkaConsumer<String, String> consumer = null;
  42.        try {
  43.            FileInputStream inputStream = new FileInputStream(new File(consumerProPath)) ;
  44.            Properties properties = new Properties();
  45.            properties.load(inputStream);
  46.            consumer = new KafkaConsumer<String, String>(properties);
  47.            consumer.subscribe(Arrays.asList(topic));

  48.        } catch (IOException e) {
  49.            LOGGER.error("加载consumer.props文件出错", e);
  50.        }
  51.        return consumer;
  52.    }

  53.    public static void main(String[] args) {
  54.        if (initCheck()){
  55.            return;
  56.        }

  57.        int totalCount = 0 ;
  58.        long totalMin = 0L ;
  59.        int count = 0;
  60.        KafkaConsumer<String, String> consumer = initKafkaConsumer();

  61.        long startTime = System.currentTimeMillis() ;
  62.        //消费消息
  63.        while (true) {
  64.            ConsumerRecords<String, String> records = consumer.poll(200);
  65.            if (records.count() <= 0){
  66.                continue ;
  67.            }
  68.            LOGGER.debug("本次获取:"+records.count());
  69.            count += records.count() ;

  70.            long endTime = System.currentTimeMillis() ;
  71.            LOGGER.debug("count=" +count) ;
  72.            if (count >= 10000 ){
  73.                totalCount += count ;
  74.                LOGGER.info("this consumer {} record,use {} milliseconds",count,endTime-startTime);
  75.                totalMin += (endTime-startTime) ;
  76.                startTime = System.currentTimeMillis() ;
  77.                count = 0 ;
  78.            }
  79.            LOGGER.debug("end totalCount={},min={}",totalCount,totalMin);

  80.            /*for (ConsumerRecord<String, String> record : records) {
  81.                record.value() ;
  82.                JsonNode msg = null;
  83.                try {
  84.                    msg = mapper.readTree(record.value());
  85.                } catch (IOException e) {
  86.                    LOGGER.error("消费消息出错", e);
  87.                }
  88.                LOGGER.info("kafka receive = "+msg.toString());
  89.            }*/


  90.        }
  91.    }
  92. }

配合以下启动参数:

  1. -Dlog_path=/log/consumer.log -Dtopic=test -Dconsumer_pro_path=consumer.properties

其中采用了轮询的方式获取消息,并且记录了消费过程中的数据。

消费者采用的配置:

  1. bootstrap.servers=192.168.1.2:9094
  2. group.id=group1
  3. # 自动提交
  4. enable.auto.commit=true
  5. key.deserializer=org.apache.kafka.common.serialization.StringDeserializer
  6. value.deserializer=org.apache.kafka.common.serialization.StringDeserializer
  7. # fast session timeout makes it more fun to play with failover
  8. session.timeout.ms=10000
  9. # These buffer sizes seem to be needed to avoid consumer switching to
  10. # a mode where it processes one bufferful every 5 seconds with multiple
  11. # timeouts along the way.  No idea why this happens.
  12. fetch.min.bytes=50000
  13. receive.buffer.bytes=262144
  14. max.partition.fetch.bytes=2097152

为了简便我采用的是自动提交 ​offset​。

消息存放机制

谈到 ​offset​就必须得谈谈Kafka的消息存放机制.

Kafka​的消息不会因为消费了就会立即删除,所有的消息都会持久化到日志文件,并配置有过期时间,到了时间会自动删除过期数据,并且不会管其中的数据是否被消费过。

由于这样的机制就必须的有一个标志来表明哪些数据已经被消费过了, ​offset(偏移量)​​就是这样的作用,它类似于指针指向某个数据,当消费之后 ​offset​​就会线性的向前移动,这样一来的话消息是可以被任意消费的,只要我们修改 ​offset​的值即可。

消费过程中还有一个值得注意的是:

同一个consumer group(group.id相等)下只能有一个消费者可以消费,这个刚开始确实会让很多人踩坑。

多线程消费

针对于单线程消费实现起来自然是比较简单,但是效率也是要大打折扣的。

为此我做了一个测试,使用之前的单线程消费120009条数据的结果如下:

SSM(十七) MQ应用_apache_04

总共花了12450毫秒。

那么换成多线程消费怎么实现呢?

我们可以利用 ​partition​​的分区特性来提高消费能力,单线程的时候等于是一个线程要把所有分区里的数据都消费一遍,如果换成多线程就可以让一个线程只消费一个分区,这样效率自然就提高了,所以线程数 ​coreSize<=partition​。

首先来看下入口:

  1. public class ConsumerThreadMain {
  2.    private static String brokerList = "localhost:9094";
  3.    private static String groupId = "group1";
  4.    private static String topic = "test";
  5.    /**
  6.     * 线程数量
  7.     */
  8.    private static int threadNum = 3;
  9.    public static void main(String[] args) {
  10.        ConsumerGroup consumerGroup = new ConsumerGroup(threadNum, groupId, topic, brokerList);
  11.        consumerGroup.execute();
  12.    }
  13. }

其中的 ​ConsumerGroup​类:

  1. public class ConsumerGroup {
  2.    private static Logger LOGGER = LoggerFactory.getLogger(ConsumerGroup.class);
  3.    /**
  4.     * 线程池
  5.     */
  6.    private ExecutorService threadPool;
  7.    private List<ConsumerCallable> consumers ;
  8.    public ConsumerGroup(int threadNum, String groupId, String topic, String brokerList) {
  9.        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
  10.                .setNameFormat("consumer-pool-%d").build();
  11.        threadPool = new ThreadPoolExecutor(threadNum, threadNum,
  12.                0L, TimeUnit.MILLISECONDS,
  13.                new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
  14.        consumers = new ArrayList<ConsumerCallable>(threadNum);
  15.        for (int i = 0; i < threadNum; i++) {
  16.            ConsumerCallable consumerThread = new ConsumerCallable(brokerList, groupId, topic);
  17.            consumers.add(consumerThread);
  18.        }
  19.    }
  20.    /**
  21.     * 执行任务
  22.     */
  23.    public void execute() {
  24.        long startTime = System.currentTimeMillis() ;
  25.        for (ConsumerCallable runnable : consumers) {
  26.            Future<ConsumerFuture> future = threadPool.submit(runnable) ;
  27.        }
  28.        if (threadPool.isShutdown()){
  29.            long endTime = System.currentTimeMillis() ;
  30.            LOGGER.info("main thread use {} Millis" ,endTime -startTime) ;
  31.        }
  32.        threadPool.shutdown();
  33.    }
  34. }

最后真正的执行逻辑 ​ConsumerCallable​:

  1. public class ConsumerCallable implements Callable<ConsumerFuture> {
  2.    private static Logger LOGGER = LoggerFactory.getLogger(ConsumerCallable.class);
  3.    private AtomicInteger totalCount = new AtomicInteger() ;
  4.    private AtomicLong totalTime = new AtomicLong() ;
  5.    private AtomicInteger count = new AtomicInteger() ;
  6.    /**
  7.     * 每个线程维护KafkaConsumer实例
  8.     */
  9.    private final KafkaConsumer<String, String> consumer;
  10.    public ConsumerCallable(String brokerList, String groupId, String topic) {
  11.        Properties props = new Properties();
  12.        props.put("bootstrap.servers", brokerList);
  13.        props.put("group.id", groupId);
  14.        //自动提交位移
  15.        props.put("enable.auto.commit", "true");
  16.        props.put("auto.commit.interval.ms", "1000");
  17.        props.put("session.timeout.ms", "30000");
  18.        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
  19.        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
  20.        this.consumer = new KafkaConsumer<>(props);
  21.        consumer.subscribe(Arrays.asList(topic));
  22.    }
  23.    /**
  24.     * Computes a result, or throws an exception if unable to do so.
  25.     *
  26.     * @return computed result
  27.     * @throws Exception if unable to compute a result
  28.     */
  29.    @Override
  30.    public ConsumerFuture call() throws Exception {
  31.        boolean flag = true;
  32.        int failPollTimes = 0 ;
  33.        long startTime = System.currentTimeMillis() ;
  34.        while (flag) {
  35.            // 使用200ms作为获取超时时间
  36.            ConsumerRecords<String, String> records = consumer.poll(200);
  37.            if (records.count() <= 0){
  38.                failPollTimes ++ ;
  39.                if (failPollTimes >= 20){
  40.                    LOGGER.debug("达到{}次数,退出 ",failPollTimes);
  41.                    flag = false ;
  42.                }
  43.                continue ;
  44.            }
  45.            //获取到之后则清零
  46.            failPollTimes = 0 ;
  47.            LOGGER.debug("本次获取:"+records.count());
  48.            count.addAndGet(records.count()) ;
  49.            totalCount.addAndGet(count.get()) ;
  50.            long endTime = System.currentTimeMillis() ;
  51.            if (count.get() >= 10000 ){
  52.                LOGGER.info("this consumer {} record,use {} milliseconds",count,endTime-startTime);
  53.                totalTime.addAndGet(endTime-startTime) ;
  54.                startTime = System.currentTimeMillis() ;
  55.                count = new AtomicInteger();
  56.            }
  57.            LOGGER.debug("end totalCount={},min={}",totalCount,totalTime);
  58.            /*for (ConsumerRecord<String, String> record : records) {
  59.                // 简单地打印消息
  60.                LOGGER.debug(record.value() + " consumed " + record.partition() +
  61.                        " message with offset: " + record.offset());
  62.            }*/
  63.        }
  64.        ConsumerFuture consumerFuture = new ConsumerFuture(totalCount.get(),totalTime.get()) ;
  65.        return consumerFuture ;
  66.    }
  67. }

理一下逻辑:

其实就是初始化出三个消费者实例,用于三个线程消费。其中加入了一些统计,最后也是消费120009条数据结果如下。

SSM(十七) MQ应用_kafka_05

由于是并行运行,可见消费120009条数据可以提高2秒左右,当数据以更高的数量级提升后效果会更加明显。

但这也有一些弊端:

  • 灵活度不高,当分区数量变更之后不能自适应调整。
  • 消费逻辑和处理逻辑在同一个线程,如果处理逻辑较为复杂会影响效率,耦合也较高。当然这个处理逻辑可以再通过一个内部队列发出去由另外的程序来处理也是可以的。

总结

Kafka​​的知识点还是较多, ​Kafka​​的使用也远不这些。之后会继续分享一些关于 ​Kafka​监控等相关内容。

项目地址:https://github.com/crossoverJie/SSM.git

个人博客:http://crossoverjie.top。