1、MQ(RabbitMQ):用来管理生产者、消费者、队列、交换机(exchanges)、虚拟主机
2、Spring AMQP: 简化RabbitMQ的一套属于Spring家族的一套东西
3、WorkQueues模型:让多个人同时接收同一消息
4、啥叫Component 和Bean?
为了像静态变量一样用这个方法的实例。例如:
@Configuration
public class AppConfig {
@Bean // 关键!告诉 Spring 管理这个返回值
public DataSource dataSource() {
return new HikariDataSource();
}
}
@Service
public class UserService {
@Autowired
private DataSource dataSource; // 成功注入!
}
5、难道开着mq的时候会给后端反馈吗?告诉你发送成功的反馈。
是的。所以才会有生产者确认:none关闭生产者确认、correlated异步、simple同步
6、生产者确认:none关闭生产者确认、correlated异步、simple同步
其中none、correlated是不阻塞线程,simple阻塞线程。
none和correlated区别:
none玩完就跑,不关心是否成功
correlated要确认成功才行。
7、@Slf4j
(自动生成日志对象)
8、@Configuration
、 @Component都与@Bean配合
区别:
@Configuration 配置数据源、第三方库集成等基础设施,配置类一般用@Configuration
@Component业务逻辑、服务层、持久层 Service、Controller、Repository一般用@Component,
核心区别:Spring可以直接实例化@Component的类,但只能实例化@Configuration中被@Bean标注的方法,注意:Configuration也可以像Component一样把类本身实例化。
9、构造方法没有返回值。
public class Tool {
private final String name;
//构造方法,没有返回值
public Tool(String name) {
this.name = name;
}
public void use() {
System.out.println("Using tool: " + name);
}
10、MQ的lazy模式:
接收到消息后直接存入磁盘而非内存
消费者要消费消息时才会从磁盘中读取并加载到内存(也就是懒加载)
11、构造器和set方法啥区别?是不是一个是创造对象的时候用,一个是创造完成再更改的时候用,而没有创造对象的时候没法使用set方法?
正确。
12、对Bean的理解:假设Bean的方法是Queue lazyQueue()
S1、首先需要一个实体对象,比如:
public class Queue{
private String name ;
//constructor
public Queue(String name){
this.name=name;
}
}
S2、使用@Bean
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration // 标记为配置类
public class RabbitMQConfig {
@Bean // 声明这是一个 Spring Bean
public Queue lazyQueue() {
// 实际使用 RabbitMQ 的 QueueBuilder
return new Queue("lazy.queue") {
// 这里简化了实现,实际开发中:
// QueueBuilder.durable("lazy.queue").lazy().build()
};
}
@Bean
public Queue normalQueue() {
return new Queue("normal.queue");
}
}
S3、使用被@Bean了的Queue
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service // 标记为 Spring 服务组件
public class QueueService {
// 通过依赖注入获取 Queue 实例
private final Queue lazyQueue;
private final Queue normalQueue;
// 构造器注入(推荐)
@Autowired
public QueueService(Queue lazyQueue, Queue normalQueue) {
this.lazyQueue = lazyQueue;
this.normalQueue = normalQueue;
}
public void processQueues() {
System.out.println("使用懒加载队列: " + lazyQueue.getName());
System.out.println("使用普通队列: " + normalQueue.getName());
// 实际业务中这里会进行消息操作
// rabbitTemplate.convertAndSend(lazyQueue.getName(), message);
}
}
13、极少极少的情况会用static,final偶尔会用。
14、@RequiredArgsConstructor
@RequiredArgsConstructor是 Lombok 提供的注解,它会自动生成一个包含所有 final 字段或标记了 @NonNull
且未初始化的字段的构造方法。
原来用@Bean了的方法创造对象时,有多少private final Queue lazyQueue就要用@Autowired注入多少次。
而现在只需要对这个类使用一次@RequiredArgsConstructor就可以了。