YumiNail后端和网关初始化
This commit is contained in:
@@ -231,11 +231,14 @@
|
||||
|
||||
## 使用方式
|
||||
|
||||
### 方式一:使用测试类发送消息
|
||||
### 使用Java客户端发送消息
|
||||
|
||||
参考 `MessageProducerTest.java` 中的测试方法:
|
||||
|
||||
```java
|
||||
@Autowired
|
||||
private MessageProducerService messageProducerService;
|
||||
|
||||
@Test
|
||||
public void testSendSmsMessage() {
|
||||
MessageDTO messageDTO = new MessageDTO();
|
||||
@@ -246,37 +249,73 @@ public void testSendSmsMessage() {
|
||||
|
||||
messageProducerService.sendSmsMessage(messageDTO);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendEmailMessage() {
|
||||
MessageDTO messageDTO = new MessageDTO();
|
||||
messageDTO.setReceiver("test@example.com");
|
||||
messageDTO.setChannelType("EMAIL");
|
||||
messageDTO.setMsgType("NOTIFICATION");
|
||||
messageDTO.setSourceSystem("MessageHub");
|
||||
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("message", "这是一封测试邮件");
|
||||
messageDTO.setTemplateParams(params);
|
||||
|
||||
messageProducerService.sendEmailMessage(messageDTO);
|
||||
}
|
||||
```
|
||||
|
||||
### 方式二:使用RabbitMQ管理界面发送消息
|
||||
### 在业务代码中使用
|
||||
|
||||
1. 登录RabbitMQ管理界面:http://192.168.5.15:15672
|
||||
2. 进入Queues页面
|
||||
3. 选择对应的队列(smsQueue 或 emailQueue)
|
||||
4. 点击"Publish message"
|
||||
5. 将JSON消息体粘贴到Payload中
|
||||
6. 点击"Publish message"发送
|
||||
|
||||
### 方式三:使用RabbitMQ命令行工具发送消息
|
||||
|
||||
```bash
|
||||
# 发送短信消息
|
||||
rabbitmqadmin publish exchange=smsExchange routing_key=sms.send payload='{"receiver":"13800138000","channelType":"SMS","msgType":"VERIFICATION","sourceSystem":"TestSystem","uniqueId":"test_001"}'
|
||||
|
||||
# 发送邮件消息
|
||||
rabbitmqadmin publish exchange=emailExchange routing_key=email.send payload='{"receiver":"test@example.com","channelType":"EMAIL","msgType":"NOTIFICATION","sourceSystem":"TestSystem","uniqueId":"test_002"}'
|
||||
```java
|
||||
@Service
|
||||
public class OrderService {
|
||||
|
||||
@Autowired
|
||||
private MessageProducerService messageProducerService;
|
||||
|
||||
public void sendOrderNotification(String phone, String orderNo) {
|
||||
MessageDTO messageDTO = new MessageDTO();
|
||||
messageDTO.setReceiver(phone);
|
||||
messageDTO.setChannelType("SMS");
|
||||
messageDTO.setMsgType("NOTIFICATION");
|
||||
messageDTO.setTemplateCode("ORDER_NOTIFY");
|
||||
messageDTO.setSourceSystem("OrderSystem");
|
||||
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("orderNo", orderNo);
|
||||
params.put("productName", "iPhone 15 Pro");
|
||||
params.put("amount", "8999.00");
|
||||
messageDTO.setTemplateParams(params);
|
||||
|
||||
messageProducerService.sendSmsMessage(messageDTO);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 队列配置
|
||||
|
||||
### 统一消息交换机
|
||||
- **交换机名称**: messageExchange
|
||||
- **交换机类型**: Topic
|
||||
|
||||
### 短信队列
|
||||
- 队列名称:smsQueue
|
||||
- 交换机名称:smsExchange
|
||||
- 路由键:sms.send
|
||||
- 监听器:SmsQueueListener
|
||||
- **队列名称**: smsQueue
|
||||
- **路由键模式**: sms.# (匹配所有以sms.开头的routing key)
|
||||
- **监听器**: SmsQueueListener
|
||||
- **支持的routing key**:
|
||||
- sms.verification(验证码短信)
|
||||
- sms.notification(通知短信)
|
||||
- sms.promotion(营销短信)
|
||||
- sms.alert(告警短信)
|
||||
|
||||
### 邮件队列
|
||||
- 队列名称:emailQueue
|
||||
- 交换机名称:emailExchange
|
||||
- 路由键:email.send
|
||||
- 监听器:EmailQueueListener
|
||||
- **队列名称**: emailQueue
|
||||
- **路由键模式**: email.# (匹配所有以email.开头的routing key)
|
||||
- **监听器**: EmailQueueListener
|
||||
- **支持的routing key**:
|
||||
- email.verification(验证码邮件)
|
||||
- email.notification(通知邮件)
|
||||
- email.promotion(营销邮件)
|
||||
- email.alert(告警邮件)
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import org.springframework.amqp.core.Binding;
|
||||
import org.springframework.amqp.core.BindingBuilder;
|
||||
import org.springframework.amqp.core.FanoutExchange;
|
||||
import org.springframework.amqp.core.Queue;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 交换机队列配置
|
||||
* 该类配置了RabbitMQ的扇出型(Fanout)交换机和队列的绑定关系
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Configuration // 标记为配置类,用于定义Bean
|
||||
public class FanoutConfig {
|
||||
|
||||
// 定义扇出型交换机Bean
|
||||
// 交换机名称为"fanout.sms",类型为FanoutExchange
|
||||
@Bean // 将该方法返回的对象注册为Spring容器中的Bean
|
||||
public FanoutExchange fanoutExchange() {
|
||||
return new FanoutExchange("fanout.sms");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// 定义短信队列Bean
|
||||
// 队列名称为"smsQueue"
|
||||
@Bean // 将该方法返回的对象注册为Spring容器中的Bean
|
||||
public Queue smsQueue() {
|
||||
return new Queue("smsQueue");
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 定义绑定关系Bean
|
||||
// 将smsQueue队列绑定到fanoutExchange交换机上
|
||||
@Bean // 将该方法返回的对象注册为Spring容器中的Bean
|
||||
public Binding fanoutBinding() {
|
||||
return BindingBuilder.bind(smsQueue()).to(fanoutExchange());
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* RabbitMQ配置类
|
||||
* 用于配置RabbitMQ的队列(Queue)、交换机(Exchange)和绑定(Binding)
|
||||
* 用于配置RabbitMQ的队列、交换机和绑定
|
||||
*/
|
||||
@Configuration
|
||||
public class RabbitMQConfig {
|
||||
@@ -15,14 +15,12 @@ public class RabbitMQConfig {
|
||||
public static final String SMS_QUEUE = "smsQueue";
|
||||
// 定义邮件队列名称常量
|
||||
public static final String EMAIL_QUEUE = "emailQueue";
|
||||
// 定义短信交换机名称常量
|
||||
public static final String SMS_EXCHANGE = "smsExchange";
|
||||
// 定义邮件交换机名称常量
|
||||
public static final String EMAIL_EXCHANGE = "emailExchange";
|
||||
// 定义统一消息交换机名称常量
|
||||
public static final String MESSAGE_EXCHANGE = "messageExchange";
|
||||
// 定义短信路由键常量
|
||||
public static final String SMS_ROUTING_KEY = "sms.send";
|
||||
public static final String SMS_ROUTING_KEY = "sms.#";
|
||||
// 定义邮件路由键常量
|
||||
public static final String EMAIL_ROUTING_KEY = "email.send";
|
||||
public static final String EMAIL_ROUTING_KEY = "email.#";
|
||||
|
||||
/**
|
||||
* 配置短信队列
|
||||
@@ -43,38 +41,29 @@ public class RabbitMQConfig {
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置短信交换机
|
||||
* 配置统一消息交换机
|
||||
* @return 持久化的、自动删除的、不自动声明的主题交换机
|
||||
*/
|
||||
@Bean
|
||||
public TopicExchange smsExchange() {
|
||||
return new TopicExchange(SMS_EXCHANGE, true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置邮件交换机
|
||||
* @return 持久化的、自动删除的、不自动声明的主题交换机
|
||||
*/
|
||||
@Bean
|
||||
public TopicExchange emailExchange() {
|
||||
return new TopicExchange(EMAIL_EXCHANGE, true, false);
|
||||
public TopicExchange messageExchange() {
|
||||
return new TopicExchange(MESSAGE_EXCHANGE, true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置短信队列与交换机的绑定关系
|
||||
* @return 绑定对象,将短信队列绑定到短信交换机,并设置路由键
|
||||
* @return 绑定对象,将短信队列绑定到统一消息交换机,并设置路由键
|
||||
*/
|
||||
@Bean
|
||||
public Binding smsBinding() {
|
||||
return BindingBuilder.bind(smsQueue()).to(smsExchange()).with(SMS_ROUTING_KEY);
|
||||
return BindingBuilder.bind(smsQueue()).to(messageExchange()).with(SMS_ROUTING_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置邮件队列与交换机的绑定关系
|
||||
* @return 绑定对象,将邮件队列绑定到邮件交换机,并设置路由键
|
||||
* @return 绑定对象,将邮件队列绑定到统一消息交换机,并设置路由键
|
||||
*/
|
||||
@Bean
|
||||
public Binding emailBinding() {
|
||||
return BindingBuilder.bind(emailQueue()).to(emailExchange()).with(EMAIL_ROUTING_KEY);
|
||||
return BindingBuilder.bind(emailQueue()).to(messageExchange()).with(EMAIL_ROUTING_KEY);
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -38,12 +38,12 @@ public class MessageProducerService {
|
||||
.build();
|
||||
|
||||
rabbitTemplate.send(
|
||||
RabbitMQConfig.SMS_EXCHANGE,
|
||||
RabbitMQConfig.SMS_ROUTING_KEY,
|
||||
RabbitMQConfig.MESSAGE_EXCHANGE,
|
||||
"sms." + messageDTO.getMsgType().toLowerCase(),
|
||||
message
|
||||
);
|
||||
|
||||
log.info("短信消息已发送到队列,消息ID: {}, 手机号: {}", messageId, messageDTO.getReceiver());
|
||||
log.info("短信消息已发送到队列,消息ID: {}, 手机号: {}, 消息类型: {}", messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception e) {
|
||||
log.error("发送短信消息失败", e);
|
||||
throw new RuntimeException("发送短信消息失败: " + e.getMessage(), e);
|
||||
@@ -65,12 +65,12 @@ public class MessageProducerService {
|
||||
.build();
|
||||
|
||||
rabbitTemplate.send(
|
||||
RabbitMQConfig.EMAIL_EXCHANGE,
|
||||
RabbitMQConfig.EMAIL_ROUTING_KEY,
|
||||
RabbitMQConfig.MESSAGE_EXCHANGE,
|
||||
"email." + messageDTO.getMsgType().toLowerCase(),
|
||||
message
|
||||
);
|
||||
|
||||
log.info("邮件消息已发送到队列,消息ID: {}, 收件人: {}", messageId, messageDTO.getReceiver());
|
||||
log.info("邮件消息已发送到队列,消息ID: {}, 收件人: {}, 消息类型: {}", messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception e) {
|
||||
log.error("发送邮件消息失败", e);
|
||||
throw new RuntimeException("发送邮件消息失败: " + e.getMessage(), e);
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
wrapperVersion=3.3.4
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip
|
||||
@@ -0,0 +1,138 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.7.18</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.xiaowang</groupId>
|
||||
<artifactId>YumiNail-Core</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>YumiNail-Core</name>
|
||||
<description>YumiNail-Core - 核心业务微服务</description>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<spring-cloud.version>2021.0.8</spring-cloud.version>
|
||||
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
|
||||
<mybatis-plus.version>3.5.3.1</mybatis-plus.version>
|
||||
<druid.version>1.2.23</druid.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- Web Starter -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Redis -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- RabbitMQ -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-amqp</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Nacos Discovery -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Nacos Config -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Bootstrap for Nacos Config -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-bootstrap</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- MySQL & Druid & MyBatis-Plus -->
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
<version>${mybatis-plus.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid-spring-boot-starter</artifactId>
|
||||
<version>${druid.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Validation -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Lombok -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<!-- Test -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>${spring-cloud.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>${spring-cloud-alibaba.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.xiaowang.yuminailcore;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
||||
|
||||
@EnableDiscoveryClient
|
||||
@SpringBootApplication
|
||||
public class YumiNailCoreApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(YumiNailCoreApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.xiaowang.yuminailcore.common;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
/**
|
||||
* 全局异常处理器
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
/**
|
||||
* 处理运行时异常
|
||||
*/
|
||||
@ExceptionHandler(RuntimeException.class)
|
||||
public Result<Void> handleRuntimeException(RuntimeException e) {
|
||||
log.error("运行时异常: ", e);
|
||||
return Result.error(e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理系统异常
|
||||
*/
|
||||
@ExceptionHandler(Exception.class)
|
||||
public Result<Void> handleException(Exception e) {
|
||||
log.error("系统异常: ", e);
|
||||
return Result.error("系统繁忙,请稍后再试");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.xiaowang.yuminailcore.common;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 统一响应结果类
|
||||
*
|
||||
* @param <T> 数据类型
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Result<T> implements Serializable {
|
||||
|
||||
private Integer code;
|
||||
private String message;
|
||||
private T data;
|
||||
|
||||
public static <T> Result<T> success() {
|
||||
return new Result<>(200, "操作成功", null);
|
||||
}
|
||||
|
||||
public static <T> Result<T> success(T data) {
|
||||
return new Result<>(200, "操作成功", data);
|
||||
}
|
||||
|
||||
public static <T> Result<T> error(String message) {
|
||||
return new Result<>(500, message, null);
|
||||
}
|
||||
|
||||
public static <T> Result<T> error(Integer code, String message) {
|
||||
return new Result<>(code, message, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* MyBatis-Plus配置类
|
||||
* 配置分页、乐观锁和防止全表更新等插件
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Configuration
|
||||
@MapperScan("com.xiaowang.yuminailcore.mapper")
|
||||
public class MyBatisPlusConfig {
|
||||
|
||||
/**
|
||||
* 配置MyBatis-Plus插件
|
||||
*/
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
|
||||
// 1. 分页插件
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
|
||||
|
||||
// 2. 乐观锁插件
|
||||
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
|
||||
|
||||
// 3. 防止全表更新与删除插件
|
||||
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
|
||||
|
||||
return interceptor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* MyBatis-Plus 自动填充配置
|
||||
* 用于自动填充实体类中的创建时间、更新时间等字段
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class MyMetaObjectHandler implements MetaObjectHandler {
|
||||
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
log.info("start insert fill ....");
|
||||
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
|
||||
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.now().getClass(), LocalDateTime.now());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
log.info("start update fill ....");
|
||||
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import org.springframework.amqp.core.Binding;
|
||||
import org.springframework.amqp.core.BindingBuilder;
|
||||
import org.springframework.amqp.core.DirectExchange;
|
||||
import org.springframework.amqp.core.Queue;
|
||||
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
|
||||
import org.springframework.amqp.support.converter.MessageConverter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* RabbitMQ配置类
|
||||
* 配置交换机、队列以及消息转换器
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Configuration
|
||||
public class RabbitMQConfig {
|
||||
|
||||
/**
|
||||
* 配置消息转换器为JSON格式
|
||||
*/
|
||||
@Bean
|
||||
public MessageConverter jsonMessageConverter() {
|
||||
return new Jackson2JsonMessageConverter();
|
||||
}
|
||||
|
||||
// 示例队列和交换机配置,方便后续扩展
|
||||
public static final String EXAMPLE_QUEUE = "yuminail.example.queue";
|
||||
public static final String EXAMPLE_EXCHANGE = "yuminail.example.exchange";
|
||||
public static final String EXAMPLE_ROUTING_KEY = "yuminail.example.routing.key";
|
||||
|
||||
@Bean
|
||||
public Queue exampleQueue() {
|
||||
return new Queue(EXAMPLE_QUEUE, true);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DirectExchange exampleExchange() {
|
||||
return new DirectExchange(EXAMPLE_EXCHANGE);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding exampleBinding() {
|
||||
return BindingBuilder.bind(exampleQueue()).to(exampleExchange()).with(EXAMPLE_ROUTING_KEY);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
|
||||
import org.springframework.cache.annotation.CachingConfigurerSupport;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
/**
|
||||
* Redis配置类
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Configuration
|
||||
@EnableCaching
|
||||
public class RedisConfig extends CachingConfigurerSupport {
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
|
||||
RedisTemplate<String, Object> template = new RedisTemplate<>();
|
||||
template.setConnectionFactory(factory);
|
||||
|
||||
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
|
||||
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
|
||||
ObjectMapper om = new ObjectMapper();
|
||||
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
|
||||
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
|
||||
jackson2JsonRedisSerializer.setObjectMapper(om);
|
||||
|
||||
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
|
||||
|
||||
// key采用String的序列化方式
|
||||
template.setKeySerializer(stringRedisSerializer);
|
||||
// hash的key也采用String的序列化方式
|
||||
template.setHashKeySerializer(stringRedisSerializer);
|
||||
// value序列化方式采用jackson
|
||||
template.setValueSerializer(jackson2JsonRedisSerializer);
|
||||
// hash的value序列化方式采用jackson
|
||||
template.setHashValueSerializer(jackson2JsonRedisSerializer);
|
||||
template.afterPropertiesSet();
|
||||
|
||||
return template;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 健康检查控制器
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/health")
|
||||
public class HealthController {
|
||||
|
||||
/**
|
||||
* 服务状态检查
|
||||
*/
|
||||
@GetMapping("/check")
|
||||
public Result<String> check() {
|
||||
return Result.success("YumiNail-Core is running");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.xiaowang.yuminailcore.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 实体类基类
|
||||
* 提取公共字段,方便后续实体类扩展
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Data
|
||||
public abstract class BaseEntity {
|
||||
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
/**
|
||||
* 逻辑删除标识 (0:未删除, 1:已删除)
|
||||
*/
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package com.xiaowang.yuminailcore.utils;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Redis工具类
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Component
|
||||
public class RedisUtils {
|
||||
|
||||
@Autowired
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
/**
|
||||
* 指定缓存失效时间
|
||||
* @param key 键
|
||||
* @param time 时间(秒)
|
||||
* @return
|
||||
*/
|
||||
public boolean expire(String key, long time) {
|
||||
try {
|
||||
if (time > 0) {
|
||||
redisTemplate.expire(key, time, TimeUnit.SECONDS);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据key 获取过期时间
|
||||
* @param key 键 不能为null
|
||||
* @return 时间(秒) 返回0代表为永久有效
|
||||
*/
|
||||
public long getExpire(String key) {
|
||||
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断key是否存在
|
||||
* @param key 键
|
||||
* @return true 存在 false不存在
|
||||
*/
|
||||
public boolean hasKey(String key) {
|
||||
try {
|
||||
return redisTemplate.hasKey(key);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除缓存
|
||||
* @param key 可以传一个值 或多个
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public void del(String... key) {
|
||||
if (key != null && key.length > 0) {
|
||||
if (key.length == 1) {
|
||||
redisTemplate.delete(key[0]);
|
||||
} else {
|
||||
redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================String=============================
|
||||
/**
|
||||
* 普通缓存获取
|
||||
* @param key 键
|
||||
* @return 值
|
||||
*/
|
||||
public Object get(String key) {
|
||||
return key == null ? null : redisTemplate.opsForValue().get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通缓存放入
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return true成功 false失败
|
||||
*/
|
||||
public boolean set(String key, Object value) {
|
||||
try {
|
||||
redisTemplate.opsForValue().set(key, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通缓存放入并设置时间
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
|
||||
* @return true成功 false 失败
|
||||
*/
|
||||
public boolean set(String key, Object value, long time) {
|
||||
try {
|
||||
if (time > 0) {
|
||||
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
|
||||
} else {
|
||||
set(key, value);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ================================Hash=================================
|
||||
/**
|
||||
* HashGet
|
||||
* @param key 键 不能为null
|
||||
* @param item 项 不能为null
|
||||
* @return 值
|
||||
*/
|
||||
public Object hget(String key, String item) {
|
||||
return redisTemplate.opsForHash().get(key, item);
|
||||
}
|
||||
|
||||
/**
|
||||
* 向一张hash表中放入数据,如果不存在将创建
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param value 值
|
||||
* @return true 成功 false失败
|
||||
*/
|
||||
public boolean hset(String key, String item, Object value) {
|
||||
try {
|
||||
redisTemplate.opsForHash().put(key, item, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 向一张hash表中放入数据,如果不存在将创建
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param value 值
|
||||
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
|
||||
* @return true 成功 false失败
|
||||
*/
|
||||
public boolean hset(String key, String item, Object value, long time) {
|
||||
try {
|
||||
redisTemplate.opsForHash().put(key, item, value);
|
||||
if (time > 0) {
|
||||
expire(key, time);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取hashKey对应的所有键值
|
||||
* @param key 键
|
||||
* @return 对应的多个键值
|
||||
*/
|
||||
public Map<Object, Object> hmget(String key) {
|
||||
return redisTemplate.opsForHash().entries(key);
|
||||
}
|
||||
|
||||
// ============================set=============================
|
||||
/**
|
||||
* 根据key获取Set中的所有值
|
||||
* @param key 键
|
||||
* @return
|
||||
*/
|
||||
public Set<Object> sGet(String key) {
|
||||
try {
|
||||
return redisTemplate.opsForSet().members(key);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据放入set缓存
|
||||
* @param key 键
|
||||
* @param values 值 可以是多个
|
||||
* @return 成功个数
|
||||
*/
|
||||
public long sSet(String key, Object... values) {
|
||||
try {
|
||||
return redisTemplate.opsForSet().add(key, values);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// ===============================list=================================
|
||||
/**
|
||||
* 获取list缓存的内容
|
||||
* @param key 键
|
||||
* @param start 开始
|
||||
* @param end 结束 0 到 -1代表所有值
|
||||
* @return
|
||||
*/
|
||||
public List<Object> lGet(String key, long start, long end) {
|
||||
try {
|
||||
return redisTemplate.opsForList().range(key, start, end);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, Object value) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPush(key, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
spring.application.name=YumiNail-Core
|
||||
@@ -0,0 +1,10 @@
|
||||
server:
|
||||
port: 8081
|
||||
|
||||
spring:
|
||||
profiles:
|
||||
active: dev
|
||||
|
||||
# 日志配置
|
||||
logging:
|
||||
config: classpath:log4j2.xml
|
||||
@@ -0,0 +1,57 @@
|
||||
spring:
|
||||
application:
|
||||
name: yuminail-core
|
||||
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
# Nacos集群地址 (从MessageHub参考)
|
||||
server-addr: 192.168.5.101:8848,192.168.5.102:8848,192.168.5.103:8848
|
||||
# 命名空间ID (要求为YumiNail)
|
||||
namespace: YumiNail
|
||||
# 分组名称
|
||||
group: DEFAULT_GROUP
|
||||
# 服务名称
|
||||
service: ${spring.application.name}
|
||||
# 是否启用服务发现
|
||||
enabled: true
|
||||
# 是否启用服务注册
|
||||
register-enabled: true
|
||||
# Nacos认证用户名
|
||||
username: xiaowang
|
||||
# Nacos认证密码
|
||||
password: 122503wcy....
|
||||
config:
|
||||
# Nacos配置中心集群地址
|
||||
server-addr: 192.168.5.101:8848,192.168.5.102:8848,192.168.5.103:8848
|
||||
# 配置中心命名空间
|
||||
namespace: YumiNail
|
||||
# 配置分组
|
||||
group: DEFAULT_GROUP
|
||||
# 配置文件名称
|
||||
name: yuminail-core.yaml
|
||||
# 配置文件扩展名
|
||||
file-extension: yaml
|
||||
# 是否启用配置中心
|
||||
enabled: true
|
||||
# Nacos认证用户名
|
||||
username: xiaowang
|
||||
# Nacos认证密码
|
||||
password: 122503wcy....
|
||||
# 共享配置文件列表 (参考MessageHub)
|
||||
shared-configs:
|
||||
- data-id: rabbitmq.yaml
|
||||
group: DEFAULT_GROUP
|
||||
refresh: true
|
||||
- data-id: datasource.yaml
|
||||
group: DEFAULT_GROUP
|
||||
refresh: true
|
||||
- data-id: mybatis-plus.yaml
|
||||
group: DEFAULT_GROUP
|
||||
refresh: true
|
||||
- data-id: logging.yaml
|
||||
group: DEFAULT_GROUP
|
||||
refresh: true
|
||||
- data-id: redis.yaml
|
||||
group: DEFAULT_GROUP
|
||||
refresh: true
|
||||
@@ -0,0 +1,62 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
<Properties>
|
||||
<Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property>
|
||||
<Property name="LOG_HOME">E:/code/xiaowang/YumiNail-Core/logs</Property>
|
||||
</Properties>
|
||||
|
||||
<Appenders>
|
||||
<Console name="Console" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="${LOG_PATTERN}"/>
|
||||
</Console>
|
||||
|
||||
<RollingFile name="RollingFile" fileName="${LOG_HOME}/yuminail-core.log"
|
||||
filePattern="${LOG_HOME}/yuminail-core-%d{yyyy-MM-dd}-%i.log.gz">
|
||||
<PatternLayout pattern="${LOG_PATTERN}"/>
|
||||
<Policies>
|
||||
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
|
||||
<SizeBasedTriggeringPolicy size="100 MB"/>
|
||||
</Policies>
|
||||
<DefaultRolloverStrategy max="30">
|
||||
<Delete basePath="${LOG_HOME}" maxDepth="1">
|
||||
<IfFileName glob="yuminail-core-*.log.gz"/>
|
||||
<IfLastModified age="30d"/>
|
||||
</Delete>
|
||||
</DefaultRolloverStrategy>
|
||||
</RollingFile>
|
||||
|
||||
<RollingFile name="ErrorRollingFile" fileName="${LOG_HOME}/yuminail-core-error.log"
|
||||
filePattern="${LOG_HOME}/yuminail-core-error-%d{yyyy-MM-dd}-%i.log.gz">
|
||||
<PatternLayout pattern="${LOG_PATTERN}"/>
|
||||
<ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
|
||||
<Policies>
|
||||
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
|
||||
<SizeBasedTriggeringPolicy size="100 MB"/>
|
||||
</Policies>
|
||||
<DefaultRolloverStrategy max="30">
|
||||
<Delete basePath="${LOG_HOME}" maxDepth="1">
|
||||
<IfFileName glob="yuminail-core-error-*.log.gz"/>
|
||||
<IfLastModified age="30d"/>
|
||||
</Delete>
|
||||
</DefaultRolloverStrategy>
|
||||
</RollingFile>
|
||||
</Appenders>
|
||||
|
||||
<Loggers>
|
||||
<Root level="INFO">
|
||||
<AppenderRef ref="Console"/>
|
||||
<AppenderRef ref="RollingFile"/>
|
||||
<AppenderRef ref="ErrorRollingFile"/>
|
||||
</Root>
|
||||
|
||||
<Logger name="com.xiaowang.yuminailcore" level="DEBUG" additivity="false">
|
||||
<AppenderRef ref="Console"/>
|
||||
<AppenderRef ref="RollingFile"/>
|
||||
<AppenderRef ref="ErrorRollingFile"/>
|
||||
</Logger>
|
||||
|
||||
<Logger name="org.springframework" level="INFO"/>
|
||||
<Logger name="com.alibaba.nacos" level="INFO"/>
|
||||
<Logger name="org.mybatis" level="DEBUG"/>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
@@ -0,0 +1,113 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.7.18</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.xiaowang</groupId>
|
||||
<artifactId>YumiNail-Gateway</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>YumiNail-Gateway</name>
|
||||
<description>YumiNail-Gateway - 服务网关</description>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<spring-cloud.version>2021.0.8</spring-cloud.version>
|
||||
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- Spring Cloud Gateway -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-gateway</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Nacos Discovery -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Nacos Config -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Bootstrap for Nacos Config -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-bootstrap</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- LoadBalancer -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Redis (用于Token校验等) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Lombok -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<!-- Test -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>${spring-cloud.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>${spring-cloud-alibaba.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.xiaowang.yumitailgateway;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
||||
|
||||
/**
|
||||
* YumiNail 网关启动类
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@EnableDiscoveryClient
|
||||
@SpringBootApplication
|
||||
public class YumiNailGatewayApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(YumiNailGatewayApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.xiaowang.yumitailgateway.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 网关白名单配置
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "yuminail.gateway")
|
||||
public class GatewayConfig {
|
||||
|
||||
/**
|
||||
* 白名单路径列表
|
||||
*/
|
||||
private List<String> whitelist;
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.xiaowang.yumitailgateway.filter;
|
||||
|
||||
import com.xiaowang.yumitailgateway.config.GatewayConfig;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
|
||||
import org.springframework.cloud.gateway.filter.GlobalFilter;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.server.reactive.ServerHttpRequest;
|
||||
import org.springframework.http.server.reactive.ServerHttpResponse;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 全局认证过滤器
|
||||
* 负责 Token 校验和白名单过滤
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AuthGlobalFilter implements GlobalFilter, Ordered {
|
||||
|
||||
@Autowired
|
||||
private GatewayConfig gatewayConfig;
|
||||
|
||||
private final AntPathMatcher pathMatcher = new AntPathMatcher();
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
|
||||
ServerHttpRequest request = exchange.getRequest();
|
||||
String path = request.getURI().getPath();
|
||||
|
||||
log.info("网关接收到请求: {}", path);
|
||||
|
||||
// 1. 白名单校验
|
||||
if (isWhitelist(path)) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
|
||||
// 2. Token 校验
|
||||
String token = request.getHeaders().getFirst("Authorization");
|
||||
if (!StringUtils.hasText(token)) {
|
||||
return unAuthorized(exchange, "未携带Token,拒绝访问");
|
||||
}
|
||||
|
||||
// TODO: 这里可以集成 Redis 进一步校验 Token 的合法性和有效期
|
||||
// String userJson = redisTemplate.opsForValue().get("TOKEN:" + token);
|
||||
// if (!StringUtils.hasText(userJson)) {
|
||||
// return unAuthorized(exchange, "Token已过期或非法");
|
||||
// }
|
||||
|
||||
// 3. 示例:简单的 Token 校验逻辑(后续可扩展)
|
||||
if (!"yuminail-test-token".equals(token)) {
|
||||
// 仅做演示,实际应解析JWT或查询Redis
|
||||
// return unAuthorized(exchange, "Token校验失败");
|
||||
}
|
||||
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否在白名单中
|
||||
*/
|
||||
private boolean isWhitelist(String path) {
|
||||
if (gatewayConfig.getWhitelist() == null) {
|
||||
return false;
|
||||
}
|
||||
return gatewayConfig.getWhitelist().stream()
|
||||
.anyMatch(pattern -> pathMatcher.match(pattern, path));
|
||||
}
|
||||
|
||||
/**
|
||||
* 无权限响应处理
|
||||
*/
|
||||
private Mono<Void> unAuthorized(ServerWebExchange exchange, String msg) {
|
||||
ServerHttpResponse response = exchange.getResponse();
|
||||
response.setStatusCode(HttpStatus.UNAUTHORIZED);
|
||||
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
|
||||
|
||||
String result = "{\"code\": 401, \"message\": \"" + msg + "\", \"data\": null}";
|
||||
DataBuffer buffer = response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
return response.writeWith(Mono.just(buffer));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return -1; // 优先级最高
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
server:
|
||||
port: 8888
|
||||
|
||||
spring:
|
||||
profiles:
|
||||
active: dev
|
||||
|
||||
cloud:
|
||||
gateway:
|
||||
discovery:
|
||||
locator:
|
||||
enabled: true # 开启从注册中心动态创建路由的功能
|
||||
lower-case-service-id: true # 使用小写服务名
|
||||
routes:
|
||||
- id: yuminail-core-route
|
||||
uri: lb://yuminail-core
|
||||
predicates:
|
||||
- Path=/core/**
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
|
||||
# 自定义配置:白名单
|
||||
yuminail:
|
||||
gateway:
|
||||
whitelist:
|
||||
- /auth/login
|
||||
- /auth/register
|
||||
- /health/check
|
||||
- /doc.html
|
||||
- /webjars/**
|
||||
- /v2/api-docs/**
|
||||
- /swagger-resources/**
|
||||
@@ -0,0 +1,24 @@
|
||||
spring:
|
||||
application:
|
||||
name: yuminail-gateway
|
||||
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
server-addr: 192.168.5.101:8848,192.168.5.102:8848,192.168.5.103:8848
|
||||
namespace: YumiNail
|
||||
group: DEFAULT_GROUP
|
||||
service: ${spring.application.name}
|
||||
config:
|
||||
server-addr: 192.168.5.101:8848,192.168.5.102:8848,192.168.5.103:8848
|
||||
namespace: YumiNail
|
||||
group: DEFAULT_GROUP
|
||||
name: yuminail-gateway.yaml
|
||||
file-extension: yaml
|
||||
shared-configs:
|
||||
- data-id: redis.yaml
|
||||
group: DEFAULT_GROUP
|
||||
refresh: true
|
||||
- data-id: logging.yaml
|
||||
group: DEFAULT_GROUP
|
||||
refresh: true
|
||||
Reference in New Issue
Block a user