diff --git a/MessageHub/MESSAGE_EXAMPLES.md b/MessageHub/MESSAGE_EXAMPLES.md index e22038c7..9dd785ae 100644 --- a/MessageHub/MESSAGE_EXAMPLES.md +++ b/MessageHub/MESSAGE_EXAMPLES.md @@ -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 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 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 \ No newline at end of file +- **队列名称**: emailQueue +- **路由键模式**: email.# (匹配所有以email.开头的routing key) +- **监听器**: EmailQueueListener +- **支持的routing key**: + - email.verification(验证码邮件) + - email.notification(通知邮件) + - email.promotion(营销邮件) + - email.alert(告警邮件) \ No newline at end of file diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/config/FanoutConfig.java b/MessageHub/src/main/java/com/xiaowang/messagehub/config/FanoutConfig.java deleted file mode 100644 index 8f0fc3b3..00000000 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/config/FanoutConfig.java +++ /dev/null @@ -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()); - } -} diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java b/MessageHub/src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java index 23f5c5e8..1b6d0b7b 100644 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java @@ -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); } } \ No newline at end of file diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/service/MessageProducerService.java b/MessageHub/src/main/java/com/xiaowang/messagehub/service/MessageProducerService.java index 583599bc..9b0e05aa 100644 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/service/MessageProducerService.java +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/service/MessageProducerService.java @@ -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); diff --git a/YumiNail-Core/.mvn/wrapper/maven-wrapper.properties b/YumiNail-Core/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..8dea6c22 --- /dev/null +++ b/YumiNail-Core/.mvn/wrapper/maven-wrapper.properties @@ -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 diff --git a/YumiNail-Core/pom.xml b/YumiNail-Core/pom.xml new file mode 100644 index 00000000..47efa8af --- /dev/null +++ b/YumiNail-Core/pom.xml @@ -0,0 +1,138 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.7.18 + + + + com.xiaowang + YumiNail-Core + 0.0.1-SNAPSHOT + YumiNail-Core + YumiNail-Core - 核心业务微服务 + + + 17 + 2021.0.8 + 2021.0.5.0 + 3.5.3.1 + 1.2.23 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + org.springframework.boot + spring-boot-starter-amqp + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config + + + + + org.springframework.cloud + spring-cloud-starter-bootstrap + + + + + com.mysql + mysql-connector-j + runtime + + + com.baomidou + mybatis-plus-boot-starter + ${mybatis-plus.version} + + + com.alibaba + druid-spring-boot-starter + ${druid.version} + + + + + org.springframework.boot + spring-boot-starter-validation + + + + + org.projectlombok + lombok + true + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + com.alibaba.cloud + spring-cloud-alibaba-dependencies + ${spring-cloud-alibaba.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/YumiNailCoreApplication.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/YumiNailCoreApplication.java new file mode 100644 index 00000000..d6c8614e --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/YumiNailCoreApplication.java @@ -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); + } + +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/common/GlobalExceptionHandler.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/common/GlobalExceptionHandler.java new file mode 100644 index 00000000..acf1acc4 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/common/GlobalExceptionHandler.java @@ -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 handleRuntimeException(RuntimeException e) { + log.error("运行时异常: ", e); + return Result.error(e.getMessage()); + } + + /** + * 处理系统异常 + */ + @ExceptionHandler(Exception.class) + public Result handleException(Exception e) { + log.error("系统异常: ", e); + return Result.error("系统繁忙,请稍后再试"); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/common/Result.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/common/Result.java new file mode 100644 index 00000000..7188ba9e --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/common/Result.java @@ -0,0 +1,40 @@ +package com.xiaowang.yuminailcore.common; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * 统一响应结果类 + * + * @param 数据类型 + * @author xiaowang + * @date 2026-02-12 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Result implements Serializable { + + private Integer code; + private String message; + private T data; + + public static Result success() { + return new Result<>(200, "操作成功", null); + } + + public static Result success(T data) { + return new Result<>(200, "操作成功", data); + } + + public static Result error(String message) { + return new Result<>(500, message, null); + } + + public static Result error(Integer code, String message) { + return new Result<>(code, message, null); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/MyBatisPlusConfig.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/MyBatisPlusConfig.java new file mode 100644 index 00000000..51259097 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/MyBatisPlusConfig.java @@ -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; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/MyMetaObjectHandler.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/MyMetaObjectHandler.java new file mode 100644 index 00000000..88a017fd --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/MyMetaObjectHandler.java @@ -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()); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RabbitMQConfig.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RabbitMQConfig.java new file mode 100644 index 00000000..86698fc7 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RabbitMQConfig.java @@ -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); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RedisConfig.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RedisConfig.java new file mode 100644 index 00000000..10a2b7e4 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RedisConfig.java @@ -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 redisTemplate(RedisConnectionFactory factory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(factory); + + // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值 + Jackson2JsonRedisSerializer 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; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/HealthController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/HealthController.java new file mode 100644 index 00000000..9f189efe --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/HealthController.java @@ -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 check() { + return Result.success("YumiNail-Core is running"); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BaseEntity.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BaseEntity.java new file mode 100644 index 00000000..08f87f5e --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BaseEntity.java @@ -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; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/utils/RedisUtils.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/utils/RedisUtils.java new file mode 100644 index 00000000..7db691d2 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/utils/RedisUtils.java @@ -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 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) 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 hmget(String key) { + return redisTemplate.opsForHash().entries(key); + } + + // ============================set============================= + /** + * 根据key获取Set中的所有值 + * @param key 键 + * @return + */ + public Set 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 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; + } + } +} diff --git a/YumiNail-Core/src/main/resources/application.properties b/YumiNail-Core/src/main/resources/application.properties new file mode 100644 index 00000000..b26f6687 --- /dev/null +++ b/YumiNail-Core/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=YumiNail-Core diff --git a/YumiNail-Core/src/main/resources/application.yaml b/YumiNail-Core/src/main/resources/application.yaml new file mode 100644 index 00000000..f6c06f9c --- /dev/null +++ b/YumiNail-Core/src/main/resources/application.yaml @@ -0,0 +1,10 @@ +server: + port: 8081 + +spring: + profiles: + active: dev + +# 日志配置 +logging: + config: classpath:log4j2.xml diff --git a/YumiNail-Core/src/main/resources/bootstrap.yaml b/YumiNail-Core/src/main/resources/bootstrap.yaml new file mode 100644 index 00000000..9dddd165 --- /dev/null +++ b/YumiNail-Core/src/main/resources/bootstrap.yaml @@ -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 diff --git a/YumiNail-Core/src/main/resources/log4j2.xml b/YumiNail-Core/src/main/resources/log4j2.xml new file mode 100644 index 00000000..ee4f486f --- /dev/null +++ b/YumiNail-Core/src/main/resources/log4j2.xml @@ -0,0 +1,62 @@ + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n + E:/code/xiaowang/YumiNail-Core/logs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/YumiNail-Gateway/pom.xml b/YumiNail-Gateway/pom.xml new file mode 100644 index 00000000..4a185329 --- /dev/null +++ b/YumiNail-Gateway/pom.xml @@ -0,0 +1,113 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.7.18 + + + + com.xiaowang + YumiNail-Gateway + 0.0.1-SNAPSHOT + YumiNail-Gateway + YumiNail-Gateway - 服务网关 + + + 17 + 2021.0.8 + 2021.0.5.0 + + + + + + org.springframework.cloud + spring-cloud-starter-gateway + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config + + + + + org.springframework.cloud + spring-cloud-starter-bootstrap + + + + + org.springframework.cloud + spring-cloud-starter-loadbalancer + + + + + org.springframework.boot + spring-boot-starter-data-redis-reactive + + + + + org.projectlombok + lombok + true + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + com.alibaba.cloud + spring-cloud-alibaba-dependencies + ${spring-cloud-alibaba.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/YumiNailGatewayApplication.java b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/YumiNailGatewayApplication.java new file mode 100644 index 00000000..9570fc9b --- /dev/null +++ b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/YumiNailGatewayApplication.java @@ -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); + } + +} diff --git a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/config/GatewayConfig.java b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/config/GatewayConfig.java new file mode 100644 index 00000000..a24a6315 --- /dev/null +++ b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/config/GatewayConfig.java @@ -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 whitelist; +} diff --git a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java new file mode 100644 index 00000000..08f8230b --- /dev/null +++ b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java @@ -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 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 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; // 优先级最高 + } +} diff --git a/YumiNail-Gateway/src/main/resources/application.yaml b/YumiNail-Gateway/src/main/resources/application.yaml new file mode 100644 index 00000000..df1e1234 --- /dev/null +++ b/YumiNail-Gateway/src/main/resources/application.yaml @@ -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/** diff --git a/YumiNail-Gateway/src/main/resources/bootstrap.yaml b/YumiNail-Gateway/src/main/resources/bootstrap.yaml new file mode 100644 index 00000000..728e8912 --- /dev/null +++ b/YumiNail-Gateway/src/main/resources/bootstrap.yaml @@ -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