BBS论坛项目相关-11:Kafka异步消息队列相关

本文介绍了BBS论坛项目中如何使用Kafka作为异步消息队列,阐述了消息队列在系统解耦、扩展性和健壮性等方面的优势。详细讲解了Kafka的基本概念和Spring整合Kafka的实现方式,以及如何通过Kafka发送系统通知,显示系统通知的详情和总消息。
摘要由CSDN通过智能技术生成

BBS论坛项目相关-11:Kafka异步消息队列相关

阻塞队列:BlockingQueue

解决线程通信问题
阻塞方法:put,take
生产者消费者模式:即N个线程进行生产,同时N个线程进行消费,两种角色通过内存缓冲区进行通信,
生产者:产生数据的线程
消费者:使用数据的线程
实现类:ArrayBlockingQueue,LinkedBlockingQueue,PriorityBlockingQueue等

生产者生产数据放在阻塞队列中

class Producer implements Runnable {
   

    private BlockingQueue<Integer> queue;

    public Producer(BlockingQueue<Integer> queue) {
   
        this.queue = queue;
    }

    @Override
    public void run() {
   
        try {
   
            for (int i = 0; i < 100; i++) {
   
                Thread.sleep(20);
                queue.put(i);
                System.out.println(Thread.currentThread().getName() + "生产:" + queue.size());
            }
        } catch (Exception e) {
   
            e.printStackTrace();
        }
    }

}

消费者从队列中拿取数据消费

class Consumer implements Runnable {
   

    private BlockingQueue<Integer> queue;

    public Consumer(BlockingQueue<Integer> queue) {
   
        this.queue = queue;
    }

    @Override
    public void run() {
   
        try {
   
            while (true) {
   
                Thread.sleep(new Random().nextInt(1000));
                queue.take();
                System.out.println(Thread.currentThread().getName() + "消费:" + queue.size());
            }
        } catch (Exception e) {
   
            e.printStackTrace();
        }
    }
}

主线程
生产者和消费者公用一个阻塞队列

public class BlockingQueueTests {
   

    public static void main(String[] args) {
   
        BlockingQueue queue = new ArrayBlockingQueue(10);
        new Thread(new Producer(queue)).start();
        new Thread(new Consumer(queue)).start();
        new Thread(new Consumer(queue)).start();
        new Thread(new Consumer(queue)).start();
    }

}
消息队列

使用消息队列的好处:
解耦和扩展性,允许独立的扩展或修改,两边的处理过程,只要确保它们遵守同样的接口约束。消息队列可作为一个接口层,解耦重要的业务流程,只需要遵守约定,针对数据编程即可获取扩展能力。
健壮性:消息队列可以堆积请求,所以消费端业务即使短时间死掉,也不会影响业务的正常运行
冗余:可以采用一对多的方式,一个生产者发布消息,可以被多个订阅topic的服务消费到,供多个毫无关联的业务使用
缓冲,有助于控制和优化数据流经过系统的速度,解决生产消息和消费消息的处理速度不一致的情况。
灵活性&峰值处理能力,使关键组件顶住突发的访问压力,而不会因为突发的超负荷的请求而完全崩溃
异步通信,消息队列提供异步处理机制,允许用户把消息放入队列,并不立即处理它,往队列里放消息,在需要的时候再去处理。
消息队列的两种模式:
1 点对点(一对一,消费者主动拉取数据,消息得到后消息清除)
2 发布/订阅模式(一对多,消费者消费数据之后不会清除消息)【分为两种:消费者主动拉取数据:生产者需要时常询问有没有消息;生产者推动数据队列:由于消费者速度不一致,可能导致资源浪费或消费者崩掉】

Kafka

一个分布式发布-订阅消息系统。分布式,可划分的,冗余备份的持久性的日志服务,主要用于处理流式数据。
应用:消息系统,日志收集,用户行为跟踪,流式处理
特点:高吞吐量,消息持久化,高可靠性,高扩展性
Kafka术语 :Broker、Zookeeper、Topic、partition、Offeset、Leader Replica、Follow Replica

创建主题:kafka-topics.bat --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 --totpic test
查看主题:kafka-topics.bat --list --bootstrap-server localhost:9092
生产者发送消息:kafka-console-producer.bat --broker-list localhost:9092 --topic test
消费者命令查看命令:kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic test --from-beginning

Spring整合Kafka

引入依赖:spring-kafka
配置kafka:配置server,consumer

spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=community-consumer-group
spring.kafka.consumer.enable-auto-commit=true
spring.kafka.consumer.auto-commit-interval=3000

访问kafka:
生产者:kafkaTemplate.send(topic,content);
消费者:
@KafkaListener(topics={””})
public void handleMassage(ConsumerRecord record){}
生产者发消息是主动发送,消费者接收消息是被动接收2,只要有消息就接收。

public class KafkaTests {
   

    @Autowired
    private KafkaProducer kafkaProducer;

    @Test
    public void testKafka() {
   
        kafkaProducer.sendMessage("test", "你好");
        kafkaProducer.sendMessage("test", "在吗");

        try {
   
            Thread.sleep(1000 * 10);
        } catch (InterruptedException e) {
   
            e.printStackTrace();
        }
    }
}
@Component
class KafkaProducer {
   

    @Autowired
    private KafkaTemplate kafkaTemplate;

    public void sendMessage(String topic, String content) {
   
        kafkaTemplate.send(topic, content);
    }
}
@Component
class KafkaConsumer {
   

    @KafkaListener(topics = {
   "test"})
    public void handleMessage(ConsumerRecord record) {
   
        System.out.println(record.value());
    }
}

发送系统通知

对不同事件创建一个主题,系统发布消息后就不用管了,可以处理下一条消息,消费者自己拉取消息。生产者和消费者处理消息时是并发的,可以同时进行。
触发事件:评论后,发布通知;点赞后,发布通知;关注后,发布通知
处理事件:封装事件对象,开发事件的生产者,开发事件的消费者

创建一个事件类
包含topic,userId,entityId,entityType,entityUserId等属性,将整个事件的触发对象userid,发生事件的对象entityId,entityType以及该对象的作者entityUserId全都包含在里面,便于之后通知调用,并用一个map来存放可能出现的额外数据,便于扩展。

public class Event {
   

    private String topic;
    private int userId;
    private int entityType;
    private int entityId;
    private int entityUserId;
    private Map<String, Object> data = new HashMap<>();

    public String getTopic() {
   
        return topic;
    }
    public Event setTopic(String topic) {
   
        this.topic = topic;
        return this;
    }
    public int getUserId() {
   
        return userId;
    }
    public Event setUserId(int userId) {
   
        this.userId 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值