7.Spring Boot中使用RabbitMQ

目录


RabbitMQ专栏目录(点击进入…)



Spring Boot中使用RabbitMQ

1.导入启动器依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2.配置文件(application.yml)

server:
  port: 80
  
spring:
  #给项目取个名字
  application:
    name: rabbitmq-provider
  #配置rabbitMq 服务器
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: root
    password: root
    #虚拟主机host 可以不设置,使用server默认host
    virtual-host: TestHost

3.初始化队列、交换机。并将队列绑定至交换机(DirectRabbitConfig.java)

使用direct exchange(直连型交换机)创建。

交换机:exchange
路由key:routingkey
队列:queue

exchange和queue是需要绑定在一起的,然后消息发送到exchange再由exchange通过routingkey发送到对应的队列中

@Configuration
public class DirectRabbitConfig {
	// 队列名:TestDirectQueue
	@Bean
	public Queue TestDirectQueue() {
		// 一般设置一下队列的持久化就好,其余三个就是默认是false、false、null
		return new Queue("TestDirectQueue", true);
	}

	// Direct交换机名:TestDirectExchange
	@Bean
	DirectExchange TestDirectExchange() {
		return new DirectExchange("TestDirectExchange", true, false);
	}

	// 绑定:将队列和交换机绑定, 并设置用于匹配键:TestDirectRouting
	@Bean
	Binding bindingDirect() {
		return BindingBuilder.bind(TestDirectQueue()) // 队列
						.to(TestDirectExchange())  // 交换机
						.with("TestDirectRouting"); // 绑定键
	}

	@Bean
	DirectExchange lonelyDirectExchange() {
		return new DirectExchange("lonelyDirectExchange");
	}
}

Queue队列

// 创建一个队列是持久的、非独占的和非自动删除的
public Queue(String name) {
	this(name, true, false, false);
}

// 创建一个新的队列,给定一个名称和持久性标志。队列非独占和非自动删除
public Queue(String name, boolean durable) {
	this(name, durable, false, false, null);
}

// 构建一个新的队列,给定队列名称、持久性、独占和自动删除标志
public Queue(String name, boolean durable, boolean exclusive, boolean autoDelete) {
	this(name, durable, exclusive, autoDelete, null);
}

// 构建一个新的队列,给定一个名称、持久性标志和自动删除标志和参数
public Queue(String name, boolean durable, boolean exclusive, boolean autoDelete,
			@Nullable Map<String, Object> arguments) {
	super(arguments);
	Assert.notNull(name, "'name' cannot be null");
	this.name = name;
	this.actualName = StringUtils.hasText(name) ? name : (Base64UrlNamingStrategy.DEFAULT.generateName() + "_awaiting_declaration");
	this.durable = durable;
	this.exclusive = exclusive;
	this.autoDelete = autoDelete;
}
属性描述
name队列名称——不应该是空的;设置为“让代理生成名称”
durable持久性。声明一个持久耐用的队列(队列将在服务器重新启动仍然有效),那么它是持久的。暂存队列:当前连接有效。持久化队列(默认true):会被存储在磁盘上,当消息代理重启时仍然存在
exclusive独占。声明一个独占队列(队列只会被声明者使用)。默认false,只能被当前创建的连接使用,而且当连接关闭后队列即被删除
autoDelete自动删除。true:如果服务器在不再使用时应该删除队列,当没有生产者或者消费者使用此队列,该队列会自动删除。默认false
arguments用于声明队列的参数。默认null

AbstractExchange(抽象类)

package org.springframework.amqp.core;

public abstract class AbstractExchange extends AbstractDeclarable implements Exchange {

    // 构建一个新的持久的、非自动删除的与提供的名称的交换机
	public AbstractExchange(String name) {
		this(name, true, false);
	}
	
    // 构建一个新的交换。给定一个名称、持久性标志、自动删除标志
	public AbstractExchange(String name, boolean durable, boolean autoDelete) {
		this(name, durable, autoDelete, null);
	}
	
    // 构建一个新的交换。给定一个名称、持久性标志和自动删除标志和参数
	public AbstractExchange(String name, boolean durable, boolean autoDelete, Map<String, Object> arguments) {
		super(arguments);
		this.name = name;
		this.durable = durable;
		this.autoDelete = autoDelete;
	}
	
}
属性描述
name交换机名称
durable持久性。声明一个持久耐用的交换机(在服务器重新启动仍然有效),那么它是持久的。默认true,即持久
autoDelete自动删除。ture:如果服务器在不再使用时删除交换。默认false,即不自动删除
arguments用于声明交换机的参数

FanoutExchange(扇形交换机)、DirectExchange(直连交换机)、TopicExchange(主题交换机)、HeadersExchange(头交换机)都继承至AbstractExchange抽象类

这几个交换机都是使用super调用器父类构造方法构建交换机

public FanoutExchange(String name) {
	super(name);
}

public FanoutExchange(String name, boolean durable, boolean autoDelete) {
	super(name, durable, autoDelete);
}

public FanoutExchange(String name, boolean durable, boolean autoDelete, Map<String, Object> arguments) {
	super(name, durable, autoDelete, arguments);
}

Binding

Binding在Spring-AMQP下core中,生产者创建消息发送至exchange,消费者从队列中消费消息,队列与交换器的绑定关系便是由Binding来表示的

public class Binding extends AbstractDeclarable {

	public Binding(String destination, DestinationType destinationType, String exchange, String routingKey,@Nullable Map<String, Object> arguments) {
		super(arguments);
		this.destination = destination; // 队列
		this.destinationType = destinationType; // 交换机类型
		this.exchange = exchange; // 交换机
		this.routingKey = routingKey; // 路由键
	}

}

队列、交换机绑定(BindingBuilder)

使用BindingBuilder实例化一个Binding,其主要作用是:在配置时更加快速的创建绑定关系

Binding binding = BindingBuilder.bind(queue).to(exchange).with(routing_key);

将一个queue绑定到exchange并用routing_key作为绑定键
bind()返回的是一个DestinationConfigurer,根据参数类型是Queue还是Exchange选择调用方法

public static DestinationConfigurer bind(Queue queue) {
	return new DestinationConfigurer(queue.getName(), DestinationType.QUEUE);
}

public static DestinationConfigurer bind(Exchange exchange) {
	return new DestinationConfigurer(exchange.getName(), DestinationType.EXCHANGE);
}

DestinationConfigurer类实现了不同Exchange的绑定,用to(Exchange_Type)用参数exchange类型来创建对应的DirectExchangeRoutingKeyConfigurer,最后使用with绑定routing_key,返回一个Binding实例


4.Controller(控制器)

@RestController
public class SendMessageController {
	//使用RabbitTemplate,这提供了接收/发送等等方法
    @Autowired
    private RabbitTemplate rabbitTemplate;  
 
    @GetMapping("/sendDirectMessage")
    public String sendDirectMessage() {
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "test message, hello!";
        String createTime = LocalDateTime.now()
				.format(DateTimeFormatter
				.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String,Object> map=new HashMap<>();
        map.put("messageId",messageId);
        map.put("messageData",messageData);
        map.put("createTime",createTime);
        //将消息携带绑定键值:TestDirectRouting发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", map);
        return "ok";
    }
}
@RestController
public class DirectRabbitController {

    @Autowired
    private RabbitTemplate rabbitTemplate;
 
    @GetMapping("/sendDirectMessage/{message}")
    public void sendDirectMessage(@PathVariable("message") String message){
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = message;
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String,Object> map=new HashMap<>();
        map.put("messageId",messageId);
        map.put("messageData",messageData);
        map.put("createTime",createTime);
        rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", map);
    }
 
    @RabbitListener(queues = "TestDirectQueue")
    public void consumerDirectMessage(Map map){
        System.out.println("DirectReceiver消费者收到消息  : " + map.toString());
    }
    
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot设置RabbitMQ的最大连接数可以通过配置文件或者编程方式完成。以下是两种常用的方法: 1. 使用配置文件:在`application.properties`或`application.yml`添加以下属性来设置最大连接数: ```properties spring.rabbitmq.connectionFactory.maxConnections=10 ``` ```yaml spring: rabbitmq: connectionFactory: maxConnections: 10 ``` 2. 使用编程方式:可以通过编写Java代码来配置RabbitMQ的最大连接数。在`RabbitMQConfig`类创建连接工厂Bean时,可以设置最大连接数属性。例如: ```java @Configuration public class RabbitMQConfig { @Value("${spring.rabbitmq.host}") private String host; @Value("${spring.rabbitmq.port}") private int port; @Value("${spring.rabbitmq.username}") private String username; @Value("${spring.rabbitmq.password}") private String password; @Value("${spring.rabbitmq.connectionFactory.maxConnections}") private int maxConnections; @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port); connectionFactory.setUsername(username); connectionFactory.setPassword(password); connectionFactory.setConnectionLimit(maxConnections); return connectionFactory; } } ``` 在上面的示例,我们使用了`CachingConnectionFactory`类来创建连接工厂,并通过`setConnectionLimit()`方法设置了最大连接数。 注意:确保配置文件的属性名与Java代码的属性名一致,这样才能正确地读取和设置最大连接数。 通过以上方法,你可以在Spring Boot设置RabbitMQ的最大连接数,根据你的需求和系统资源来调整最大连接数的值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

未禾

您的支持是我最宝贵的财富!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值