Spring Boot、Redis、RabbitMQ 在項(xiàng)目中的核心作用詳解(代碼示例)
在現(xiàn)代企業(yè)級(jí)應(yīng)用開(kāi)發(fā)中,Spring Boot、Redis 和 RabbitMQ 已經(jīng)成為不可或缺的技術(shù)組件。它們各自在項(xiàng)目中扮演著重要角色,共同構(gòu)建出高性能、高可用的分布式系統(tǒng)。本文將深入剖析這三者在實(shí)際項(xiàng)目中的作用,并通過(guò)代碼示例和流程圖展示它們的實(shí)際應(yīng)用。
一、Spring Boot:快速開(kāi)發(fā)的利器
1.1 Spring Boot 的核心作用
Spring Boot 是一個(gè)基于 Spring 框架的快速開(kāi)發(fā)腳手架,其主要作用體現(xiàn)在:
- 簡(jiǎn)化配置:通過(guò)自動(dòng)配置和約定優(yōu)于配置的原則,大幅減少 XML 配置
- 快速啟動(dòng):內(nèi)嵌 Tomcat、Jetty 等 Web 容器,無(wú)需部署 WAR 包
- 生產(chǎn)就緒:提供健康檢查、指標(biāo)監(jiān)控等生產(chǎn)級(jí)特性
- 微服務(wù)支持:完美支持 Spring Cloud 微服務(wù)生態(tài)
1.2 Spring Boot 項(xiàng)目結(jié)構(gòu)
// 主啟動(dòng)類(lèi)
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
// 控制器層
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = userService.getUserById(id);
return ResponseEntity.ok(user);
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User savedUser = userService.createUser(user);
return ResponseEntity.status(HttpStatus.CREATED).body(savedUser);
}
}
// 服務(wù)層
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User not found"));
}
public User createUser(User user) {
return userRepository.save(user);
}
}
// 數(shù)據(jù)訪問(wèn)層
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
}
// 實(shí)體類(lèi)
@Entity
@Table(name = "users")
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false, unique = true)
private String email;
@CreationTimestamp
private LocalDateTime createdAt;
}1.3 Spring Boot 自動(dòng)配置原理
// 自定義 Starter 示例
@Configuration
@ConditionalOnClass(UserService.class)
@EnableConfigurationProperties(UserProperties.class)
public class UserAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public UserService userService(UserProperties properties) {
return new UserService(properties);
}
}
// 配置屬性類(lèi)
@ConfigurationProperties(prefix = "app.user")
@Data
public class UserProperties {
private String defaultName = "Default User";
private int maxAttempts = 3;
}
// META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.autoconfigure.UserAutoConfiguration1.4 Spring Boot 在項(xiàng)目中的架構(gòu)位置
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Client │───?│ Spring Boot │───?│ Database │
│ (Browser/App) │ │ Application │ │ (MySQL/PSQL) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
└──────────────│ Thymeleaf │─────────────┘
│ Templates │
└─────────────────┘二、Redis:高性能緩存與數(shù)據(jù)存儲(chǔ)
2.1 Redis 的核心作用
Redis 是一個(gè)開(kāi)源的內(nèi)存數(shù)據(jù)結(jié)構(gòu)存儲(chǔ),用作數(shù)據(jù)庫(kù)、緩存和消息代理,其主要作用:
- 緩存加速:減少數(shù)據(jù)庫(kù)訪問(wèn),提升應(yīng)用性能
- 會(huì)話(huà)存儲(chǔ):分布式會(huì)話(huà)管理
- 消息隊(duì)列:通過(guò) Pub/Sub 和 Streams 實(shí)現(xiàn)消息傳遞
- 實(shí)時(shí)數(shù)據(jù)處理:計(jì)數(shù)器、排行榜等實(shí)時(shí)功能
2.2 Redis 在 Spring Boot 中的集成
// Redis 配置類(lèi)
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 使用 Jackson2JsonRedisSerializer 序列化
Jackson2JsonRedisSerializer<Object> serializer =
new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.activateDefaultTyping(
mapper.getPolymorphicTypeValidator(),
ObjectMapper.DefaultTyping.NON_FINAL
);
serializer.setObjectMapper(mapper);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)) // 設(shè)置緩存過(guò)期時(shí)間
.disableCachingNullValues(); // 不緩存空值
return RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
}
}2.3 Redis 緩存使用示例
// 緩存服務(wù)類(lèi)
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private static final String PRODUCT_CACHE_KEY = "product:";
private static final String PRODUCT_LIST_CACHE_KEY = "products:all";
// 使用 Spring Cache 注解
@Cacheable(value = "products", key = "#id")
public Product getProductById(Long id) {
return productRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Product not found"));
}
// 手動(dòng)緩存操作
public List<Product> getAllProducts() {
// 先從緩存獲取
List<Product> products = (List<Product>) redisTemplate.opsForValue()
.get(PRODUCT_LIST_CACHE_KEY);
if (products != null) {
return products;
}
// 緩存未命中,查詢(xún)數(shù)據(jù)庫(kù)
products = productRepository.findAll();
// 寫(xiě)入緩存,設(shè)置過(guò)期時(shí)間
redisTemplate.opsForValue().set(
PRODUCT_LIST_CACHE_KEY,
products,
Duration.ofMinutes(30)
);
return products;
}
// 更新緩存
@CachePut(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
Product updated = productRepository.save(product);
// 清除列表緩存
redisTemplate.delete(PRODUCT_LIST_CACHE_KEY);
return updated;
}
// 刪除緩存
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
productRepository.deleteById(id);
redisTemplate.delete(PRODUCT_LIST_CACHE_KEY);
}
// Redis 分布式鎖示例
public boolean purchaseProduct(Long productId, Integer quantity) {
String lockKey = "lock:product:" + productId;
String requestId = UUID.randomUUID().toString();
try {
// 嘗試獲取分布式鎖
Boolean locked = redisTemplate.opsForValue().setIfAbsent(
lockKey, requestId, Duration.ofSeconds(10)
);
if (Boolean.TRUE.equals(locked)) {
// 獲取鎖成功,執(zhí)行庫(kù)存扣減
Product product = getProductById(productId);
if (product.getStock() >= quantity) {
product.setStock(product.getStock() - quantity);
updateProduct(product);
return true;
}
return false;
} else {
// 獲取鎖失敗,稍后重試
Thread.sleep(100);
return purchaseProduct(productId, quantity);
}
} catch (Exception e) {
throw new RuntimeException("Purchase failed", e);
} finally {
// 釋放鎖
if (requestId.equals(redisTemplate.opsForValue().get(lockKey))) {
redisTemplate.delete(lockKey);
}
}
}
}2.4 Redis 數(shù)據(jù)結(jié)構(gòu)應(yīng)用場(chǎng)景
@Service
public class RedisDataStructureService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// String 類(lèi)型:緩存、計(jì)數(shù)器
public void stringOperations() {
// 緩存對(duì)象
User user = new User(1L, "John Doe", "john@example.com");
redisTemplate.opsForValue().set("user:1", user);
// 計(jì)數(shù)器
redisTemplate.opsForValue().increment("page:view:home");
Long views = redisTemplate.opsForValue().increment("user:1:login:count");
}
// Hash 類(lèi)型:存儲(chǔ)對(duì)象屬性
public void hashOperations() {
redisTemplate.opsForHash().put("user:2", "name", "Jane Smith");
redisTemplate.opsForHash().put("user:2", "email", "jane@example.com");
redisTemplate.opsForHash().put("user:2", "age", "25");
String name = (String) redisTemplate.opsForHash().get("user:2", "name");
}
// List 類(lèi)型:消息隊(duì)列、最新列表
public void listOperations() {
// 最新消息列表
redisTemplate.opsForList().leftPush("recent:news", "News 1");
redisTemplate.opsForList().leftPush("recent:news", "News 2");
redisTemplate.opsForList().trim("recent:news", 0, 9); // 保持10條最新
List<Object> recentNews = redisTemplate.opsForList().range("recent:news", 0, -1);
}
// Set 類(lèi)型:標(biāo)簽、共同好友
public void setOperations() {
// 用戶(hù)標(biāo)簽
redisTemplate.opsForSet().add("user:1:tags", "vip", "active", "premium");
redisTemplate.opsForSet().add("user:2:tags", "active", "new");
// 共同標(biāo)簽
Set<Object> commonTags = redisTemplate.opsForSet().intersect("user:1:tags", "user:2:tags");
}
// Sorted Set 類(lèi)型:排行榜
public void sortedSetOperations() {
// 用戶(hù)積分排行榜
redisTemplate.opsForZSet().add("leaderboard", "user1", 1000);
redisTemplate.opsForZSet().add("leaderboard", "user2", 1500);
redisTemplate.opsForZSet().add("leaderboard", "user3", 1200);
// 獲取前10名
Set<ZSetOperations.TypedTuple<Object>> topUsers =
redisTemplate.opsForZSet().reverseRangeWithScores("leaderboard", 0, 9);
}
}2.5 Redis 在系統(tǒng)架構(gòu)中的位置
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Spring Boot │───?│ Redis │?───│ Other Services │
│ Application │ │ │ │ │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │
│ │
▼ ▼
┌─────────────────┐ ┌──────────────────┐
│ Database │ │ Message Queue │
│ (MySQL) │ │ (RabbitMQ) │
└─────────────────┘ └──────────────────┘三、RabbitMQ:可靠的消息中間件
3.1 RabbitMQ 的核心作用
RabbitMQ 是一個(gè)開(kāi)源的消息代理軟件,實(shí)現(xiàn)了高級(jí)消息隊(duì)列協(xié)議(AMQP),主要作用:
- 應(yīng)用解耦:分離系統(tǒng)組件,降低耦合度
- 異步處理:提高系統(tǒng)響應(yīng)速度
- 流量削峰:應(yīng)對(duì)突發(fā)流量,保護(hù)后端系統(tǒng)
- 消息分發(fā):實(shí)現(xiàn)發(fā)布/訂閱模式
3.2 RabbitMQ 在 Spring Boot 中的配置
// RabbitMQ 配置類(lèi)
@Configuration
public class RabbitMQConfig {
// 交換機(jī)
public static final String EXCHANGE_ORDER = "order.exchange";
public static final String EXCHANGE_NOTIFICATION = "notification.exchange";
// 隊(duì)列
public static final String QUEUE_ORDER_CREATE = "order.create.queue";
public static final String QUEUE_ORDER_CANCEL = "order.cancel.queue";
public static final String QUEUE_NOTIFICATION_EMAIL = "notification.email.queue";
public static final String QUEUE_NOTIFICATION_SMS = "notification.sms.queue";
// 路由鍵
public static final String ROUTING_KEY_ORDER_CREATE = "order.create";
public static final String ROUTING_KEY_ORDER_CANCEL = "order.cancel";
public static final String ROUTING_KEY_NOTIFICATION_ALL = "notification.#";
// 訂單交換機(jī)(Direct)
@Bean
public DirectExchange orderExchange() {
return new DirectExchange(EXCHANGE_ORDER);
}
// 通知交換機(jī)(Topic)
@Bean
public TopicExchange notificationExchange() {
return new TopicExchange(EXCHANGE_NOTIFICATION);
}
// 訂單創(chuàng)建隊(duì)列
@Bean
public Queue orderCreateQueue() {
return new Queue(QUEUE_ORDER_CREATE, true); // durable=true
}
// 訂單取消隊(duì)列
@Bean
public Queue orderCancelQueue() {
return new Queue(QUEUE_ORDER_CANCEL, true);
}
// 郵件通知隊(duì)列
@Bean
public Queue emailNotificationQueue() {
return new Queue(QUEUE_NOTIFICATION_EMAIL, true);
}
// 短信通知隊(duì)列
@Bean
public Queue smsNotificationQueue() {
return new Queue(QUEUE_NOTIFICATION_SMS, true);
}
// 綁定關(guān)系
@Bean
public Binding bindingOrderCreate(Queue orderCreateQueue, DirectExchange orderExchange) {
return BindingBuilder.bind(orderCreateQueue)
.to(orderExchange)
.with(ROUTING_KEY_ORDER_CREATE);
}
@Bean
public Binding bindingOrderCancel(Queue orderCancelQueue, DirectExchange orderExchange) {
return BindingBuilder.bind(orderCancelQueue)
.to(orderExchange)
.with(ROUTING_KEY_ORDER_CANCEL);
}
@Bean
public Binding bindingEmailNotification(Queue emailNotificationQueue, TopicExchange notificationExchange) {
return BindingBuilder.bind(emailNotificationQueue)
.to(notificationExchange)
.with(ROUTING_KEY_NOTIFICATION_ALL);
}
@Bean
public Binding bindingSmsNotification(Queue smsNotificationQueue, TopicExchange notificationExchange) {
return BindingBuilder.bind(smsNotificationQueue)
.to(notificationExchange)
.with(ROUTING_KEY_NOTIFICATION_ALL);
}
// JSON 消息轉(zhuǎn)換器
@Bean
public MessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
}3.3 RabbitMQ 消息生產(chǎn)者
@Service
public class OrderMessageProducer {
@Autowired
private RabbitTemplate rabbitTemplate;
// 發(fā)送訂單創(chuàng)建消息
public void sendOrderCreateMessage(Order order) {
try {
OrderMessage message = new OrderMessage(
order.getId(),
order.getUserId(),
order.getTotalAmount(),
order.getStatus(),
LocalDateTime.now()
);
rabbitTemplate.convertAndSend(
RabbitMQConfig.EXCHANGE_ORDER,
RabbitMQConfig.ROUTING_KEY_ORDER_CREATE,
message,
new CorrelationData(order.getId().toString())
);
log.info("Order create message sent: {}", order.getId());
} catch (Exception e) {
log.error("Failed to send order create message", e);
throw new MessageSendException("Failed to send order message");
}
}
// 發(fā)送訂單取消消息
public void sendOrderCancelMessage(Long orderId, String reason) {
OrderCancelMessage message = new OrderCancelMessage(orderId, reason, LocalDateTime.now());
rabbitTemplate.convertAndSend(
RabbitMQConfig.EXCHANGE_ORDER,
RabbitMQConfig.ROUTING_KEY_ORDER_CANCEL,
message
);
log.info("Order cancel message sent: {}", orderId);
}
// 發(fā)送通知消息
public void sendNotification(Notification notification) {
rabbitTemplate.convertAndSend(
RabbitMQConfig.EXCHANGE_NOTIFICATION,
"notification." + notification.getType(),
notification
);
}
}
// 訂單消息DTO
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OrderMessage {
private Long orderId;
private Long userId;
private BigDecimal totalAmount;
private String status;
private LocalDateTime timestamp;
}
// 訂單取消消息DTO
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OrderCancelMessage {
private Long orderId;
private String reason;
private LocalDateTime timestamp;
}3.4 RabbitMQ 消息消費(fèi)者
@Component
public class OrderMessageConsumer {
@Autowired
private InventoryService inventoryService;
@Autowired
private EmailService emailService;
@Autowired
private NotificationService notificationService;
// 處理訂單創(chuàng)建消息
@RabbitListener(queues = RabbitMQConfig.QUEUE_ORDER_CREATE)
public void handleOrderCreate(OrderMessage message) {
try {
log.info("Processing order create message: {}", message.getOrderId());
// 扣減庫(kù)存
inventoryService.deductInventory(message.getOrderId());
// 發(fā)送確認(rèn)郵件
emailService.sendOrderConfirmation(message.getOrderId());
// 記錄處理成功
log.info("Order create message processed successfully: {}", message.getOrderId());
} catch (Exception e) {
log.error("Failed to process order create message: {}", message.getOrderId(), e);
// 可以在這里實(shí)現(xiàn)重試邏輯或死信隊(duì)列處理
throw new AmqpRejectAndDontRequeueException("Processing failed");
}
}
// 處理訂單取消消息
@RabbitListener(queues = RabbitMQConfig.QUEUE_ORDER_CANCEL)
public void handleOrderCancel(OrderCancelMessage message) {
log.info("Processing order cancel message: {}", message.getOrderId());
// 恢復(fù)庫(kù)存
inventoryService.restoreInventory(message.getOrderId());
// 發(fā)送取消通知
notificationService.sendCancelNotification(message.getOrderId(), message.getReason());
}
}
// 通知消息消費(fèi)者
@Component
public class NotificationMessageConsumer {
@Autowired
private EmailService emailService;
@Autowired
private SmsService smsService;
@RabbitListener(queues = RabbitMQConfig.QUEUE_NOTIFICATION_EMAIL)
public void handleEmailNotification(Notification notification) {
log.info("Processing email notification: {}", notification);
emailService.sendNotification(notification);
}
@RabbitListener(queues = RabbitMQConfig.QUEUE_NOTIFICATION_SMS)
public void handleSmsNotification(Notification notification) {
log.info("Processing SMS notification: {}", notification);
smsService.sendNotification(notification);
}
}3.5 RabbitMQ 高級(jí)特性配置
@Configuration
public class RabbitMQAdvancedConfig {
// 死信交換機(jī)配置
public static final String DLX_EXCHANGE = "dlx.exchange";
public static final String DLX_QUEUE = "dlx.queue";
public static final String DLX_ROUTING_KEY = "dlx.routing.key";
// 重試隊(duì)列配置
public static final String RETRY_QUEUE = "order.create.retry.queue";
public static final int MAX_RETRY_COUNT = 3;
@Bean
public DirectExchange dlxExchange() {
return new DirectExchange(DLX_EXCHANGE);
}
@Bean
public Queue dlxQueue() {
return new Queue(DLX_QUEUE, true);
}
@Bean
public Binding dlxBinding() {
return BindingBuilder.bind(dlxQueue())
.to(dlxExchange())
.with(DLX_ROUTING_KEY);
}
// 帶死信隊(duì)列的訂單創(chuàng)建隊(duì)列
@Bean
public Queue orderCreateQueueWithDLX() {
Map<String, Object> args = new HashMap<>();
args.put("x-dead-letter-exchange", DLX_EXCHANGE);
args.put("x-dead-letter-routing-key", DLX_ROUTING_KEY);
args.put("x-message-ttl", 60000); // 1分鐘TTL
return new Queue(RabbitMQConfig.QUEUE_ORDER_CREATE, true, false, false, args);
}
// 消息確認(rèn)回調(diào)
@Bean
public RabbitTemplate.ConfirmCallback confirmCallback() {
return (correlationData, ack, cause) -> {
if (ack) {
log.info("Message confirmed with correlation data: {}", correlationData);
} else {
log.error("Message confirmation failed: {}, cause: {}", correlationData, cause);
}
};
}
// 消息返回回調(diào)
@Bean
public RabbitTemplate.ReturnsCallback returnsCallback() {
return returned -> {
log.error("Message returned: {}", returned);
};
}
}3.6 RabbitMQ 在系統(tǒng)架構(gòu)中的消息流
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Order Service │───?│ RabbitMQ │───?│ Inventory │
│ │ │ │ │ Service │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
└─────────────?│ Email Service │─────────────┘
└─────────────────┘
│
│
▼
┌─────────────────┐
│ SMS Service │
└─────────────────┘四、三者在項(xiàng)目中的協(xié)同工作
4.1 完整電商訂單處理流程
@Service
@Transactional
public class OrderProcessingService {
@Autowired
private OrderService orderService;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private OrderMessageProducer messageProducer;
@Autowired
private InventoryService inventoryService;
// 創(chuàng)建訂單的完整流程
public Order createOrder(OrderRequest request) {
String lockKey = "lock:user:" + request.getUserId() + ":order";
String requestId = UUID.randomUUID().toString();
try {
// 1. 獲取分布式鎖,防止重復(fù)提交
Boolean locked = redisTemplate.opsForValue()
.setIfAbsent(lockKey, requestId, Duration.ofSeconds(5));
if (!Boolean.TRUE.equals(locked)) {
throw new BusinessException("請(qǐng)勿重復(fù)提交訂單");
}
// 2. 檢查庫(kù)存(Redis 緩存)
boolean inStock = inventoryService.checkStock(request.getProductId(), request.getQuantity());
if (!inStock) {
throw new BusinessException("庫(kù)存不足");
}
// 3. 創(chuàng)建訂單
Order order = orderService.createOrder(request);
// 4. 發(fā)送訂單創(chuàng)建消息到 RabbitMQ
messageProducer.sendOrderCreateMessage(order);
// 5. 更新 Redis 中的用戶(hù)訂單緩存
updateUserOrderCache(order.getUserId(), order);
// 6. 記錄訂單創(chuàng)建日志到 Redis
logOrderCreation(order);
return order;
} finally {
// 釋放分布式鎖
if (requestId.equals(redisTemplate.opsForValue().get(lockKey))) {
redisTemplate.delete(lockKey);
}
}
}
private void updateUserOrderCache(Long userId, Order order) {
String userOrdersKey = "user:" + userId + ":orders";
// 使用 Redis List 存儲(chǔ)用戶(hù)最近訂單
redisTemplate.opsForList().leftPush(userOrdersKey, order);
redisTemplate.opsForList().trim(userOrdersKey, 0, 49); // 保留最近50條訂單
}
private void logOrderCreation(Order order) {
String orderLogKey = "order:log:" + LocalDate.now().toString();
Map<String, Object> logEntry = new HashMap<>();
logEntry.put("orderId", order.getId());
logEntry.put("userId", order.getUserId());
logEntry.put("amount", order.getTotalAmount());
logEntry.put("timestamp", LocalDateTime.now());
redisTemplate.opsForHash().put(orderLogKey, order.getId().toString(), logEntry);
}
}4.2 系統(tǒng)架構(gòu)圖
┌─────────────────────────────────────────────────────────────────┐
│ Client Layer │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Web Browser │ │ Mobile App │ │
│ └─────────────────┘ └─────────────────┘ │
│ │ │ │
└────────────┼───────────────────────────┼───────────────────────┘
│ │
▼ ▼
┌─────────────────────────────────────────────────────────────────┐
│ Spring Boot Application │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Controller │───?│ Service │ │
│ │ Layer │ │ Layer │ │
│ └─────────────────┘ └─────────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Redis Cache │ │ RabbitMQ │ │
│ │ │ │ Producer │ │
│ └─────────────────┘ └─────────────────┘ │
└────────────┼───────────────────────────┼───────────────────────┘
│ │
▼ ▼
┌─────────────────────────────────────────────────────────────────┐
│ Backend Services │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Database │ │ RabbitMQ │ │
│ │ (MySQL) │ │ Consumer │ │
│ └─────────────────┘ └─────────────────┘ │
│ │ │ │
│ │ ▼ │
│ │ ┌─────────────────┐ │
│ │ │ External │ │
│ │ │ Services │ │
│ │ │ (Email/SMS/...) │ │
│ │ └─────────────────┘ │
│ │ │
│ └───────────────────────────────────────────────────┘
│ │
└─────────────────────────────────────────────────────────────────┘4.3 性能優(yōu)化配置
# application.yml
spring:
# Redis 配置
redis:
host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379}
password: ${REDIS_PASSWORD:}
database: 0
lettuce:
pool:
max-active: 20
max-idle: 10
min-idle: 5
max-wait: 1000ms
shutdown-timeout: 100ms
# RabbitMQ 配置
rabbitmq:
host: ${RABBITMQ_HOST:localhost}
port: ${RABBITMQ_PORT:5672}
username: ${RABBITMQ_USERNAME:guest}
password: ${RABBITMQ_PASSWORD:guest}
virtual-host: /
# 確認(rèn)模式
publisher-confirm-type: correlated
publisher-returns: true
# 消費(fèi)者配置
listener:
simple:
acknowledge-mode: manual
prefetch: 10
concurrency: 5
max-concurrency: 10
retry:
enabled: true
max-attempts: 3
initial-interval: 1000ms
# 數(shù)據(jù)源配置
datasource:
url: jdbc:mysql://${DB_HOST:localhost}:3306/ecommerce
username: ${DB_USERNAME:root}
password: ${DB_PASSWORD:password}
hikari:
maximum-pool-size: 20
minimum-idle: 5
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
# 自定義配置
app:
cache:
ttl: 30m
order:
timeout: 30m
redis:
key-prefix: "app:"五、總結(jié)
通過(guò)本文的詳細(xì)講解,我們可以看到 Spring Boot、Redis 和 RabbitMQ 在現(xiàn)代分布式系統(tǒng)中各自扮演著重要角色:
- Spring Boot 提供了快速開(kāi)發(fā)的能力,通過(guò)自動(dòng)配置和豐富的 Starter 簡(jiǎn)化了項(xiàng)目搭建和配置
- Redis 作為高性能緩存和數(shù)據(jù)存儲(chǔ),顯著提升了系統(tǒng)性能并提供了豐富的數(shù)據(jù)結(jié)構(gòu)支持
- RabbitMQ 實(shí)現(xiàn)了系統(tǒng)解耦和異步處理,提高了系統(tǒng)的可擴(kuò)展性和可靠性
三者結(jié)合使用,可以構(gòu)建出高性能、高可用、易擴(kuò)展的現(xiàn)代分布式應(yīng)用系統(tǒng)。在實(shí)際項(xiàng)目中,我們需要根據(jù)具體業(yè)務(wù)場(chǎng)景合理選擇和使用這些技術(shù),充分發(fā)揮它們的優(yōu)勢(shì)。
希望本文能夠幫助大家更好地理解和使用 Spring Boot、Redis 和 RabbitMQ,在實(shí)際項(xiàng)目中構(gòu)建出更加優(yōu)秀的系統(tǒng)架構(gòu)
到此這篇關(guān)于Spring Boot、Redis、RabbitMQ 在項(xiàng)目中的核心作用詳解的文章就介紹到這了,更多相關(guān)Spring Boot、Redis、RabbitMQ 作用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在SpringBoot中通過(guò)@Value注入Map和List并使用YAML配置的詳細(xì)教程
在SpringBoot開(kāi)發(fā)中,我們經(jīng)常需要從配置文件中讀取各種參數(shù),對(duì)于簡(jiǎn)單的字符串或數(shù)值,直接使用@Value注解就可以了,但當(dāng)我們需要注入更復(fù)雜的數(shù)據(jù)結(jié)構(gòu),比如Map或者List時(shí),所以本文小編給大家介紹在SpringBoot中通過(guò)@Value注入Map和List并使用YAML配置的詳細(xì)教程2025-04-04
Java多線程中的CountDownLatch詳細(xì)解讀
這篇文章主要介紹了Java多線程中的CountDownLatch詳細(xì)解讀,一個(gè)同步輔助類(lèi),在完成一組正在其他線程中執(zhí)行的操作之前,它允許一個(gè)或多個(gè)線程一直等待,用給定的計(jì)數(shù) 初始化 CountDownLatch,需要的朋友可以參考下2023-11-11
為SpringBoot服務(wù)添加HTTPS證書(shū)的方法
這篇文章主要介紹了為SpringBoot服務(wù)添加HTTPS證書(shū)的方法,幫助大家更好的理解和使用springBoot框架,感興趣的朋友可以了解下2020-10-10
Java并發(fā)容器之ConcurrentLinkedQueue詳解
這篇文章主要介紹了Java并發(fā)容器之ConcurrentLinkedQueue詳解,加鎖隊(duì)列的實(shí)現(xiàn)較為簡(jiǎn)單,這里就略過(guò),我們來(lái)重點(diǎn)來(lái)解讀一下非阻塞隊(duì)列,2023-12-12
從點(diǎn)到面, 下面我們來(lái)看下非阻塞隊(duì)列經(jīng)典實(shí)現(xiàn)類(lèi)ConcurrentLinkedQueue,需要的朋友可以參考下
JAVA設(shè)計(jì)模式之建造者模式原理與用法詳解
這篇文章主要介紹了JAVA設(shè)計(jì)模式之建造者模式,簡(jiǎn)單說(shuō)明了建造者模式的原理、組成,并結(jié)合實(shí)例形式分析了java建造者模式的定義與用法,需要的朋友可以參考下2017-08-08
Java的Swing編程中使用SwingWorker線程模式及頂層容器
這篇文章主要介紹了在Java的Swing編程中使用SwingWorker線程模式及頂層容器的方法,適用于客戶(hù)端圖形化界面軟件的開(kāi)發(fā),需要的朋友可以參考下2016-01-01
Java?數(shù)據(jù)結(jié)構(gòu)與算法系列精講之棧
棧(stack)又名堆棧,它是一種運(yùn)算受限的線性表。限定僅在表尾進(jìn)行插入和刪除操作的線性表。這一端被稱(chēng)為棧頂,相對(duì)地,把另一端稱(chēng)為棧底,棧是基礎(chǔ)中的基礎(chǔ),如果你還沒(méi)掌握透徹就來(lái)接著往下看吧2022-02-02

