引言:
在处理秒杀场景时经常会用到rabbitmq削峰限流作用,假设我们的系统能每秒处理1000个请求,如果有上万个请求同时打进来,会造成服务器的瘫痪。
这时就需要在系统之前加一次处理,将请求发送的MQ中,再让A系统以每秒1000的速率去请求mq服务器。
代码实现:
配置文件:
spring.application.name=springboot_rabbitmq
spring.rabbitmq.host=192.168.0.102
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
spring.rabbitmq.virtual-host=/
spring.rabbitmq.listener.simple.acknowledge-mode=manual #设置手动应答
spring.rabbitmq.listener.simple.prefetch=2 #每次最多可处理信息量
消费者:
@Component
@RabbitListener(queuesToDeclare = @Queue(name = "springboot-limit"))
public class CurrentlimitCustomer {
@RabbitHandler
public void receive(String msg, Channel channel, Message message) throws IOException {
long deliveryTag = message.getMessageProperties().getDeliveryTag();
try {
Thread.sleep(1000*10);
System.out.println("=====限流====>");
System.out.println(msg);
System.out.println(channel);
System.out.println(message);
//手动签收[参数1:消息投递序号,参数2:批量签收]
channel.basicAck(deliveryTag, true);
} catch (Exception e) {
}
}
}
生产者:
@Test
public void test09() throws Exception {
for (int i = 0; i < 10 ; i++) {
rabbitTemplate.convertAndSend("springboot-limit", "限流测试");
}
Thread.sleep(1000 * 1000);
}