From b4f95f805555d740a8e188535c95c885adb3e39a Mon Sep 17 00:00:00 2001 From: zhuwenqiang Date: Sun, 12 Nov 2023 17:38:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=88=91=E7=9A=84=E7=AC=AC=E4=B8=80=E6=AC=A1?= =?UTF-8?q?=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bwie-auth/pom.xml | 55 ++++ .../java/com/bwie/auth/AuthApplication.java | 28 ++ .../auth/consumer/LoginLogQueueConsumer.java | 52 ++++ .../auth/consumer/WebsiteStatsConsumer.java | 57 ++++ .../bwie/auth/controller/AuthController.java | 86 ++++++ .../bwie/auth/feign/SystemFeignService.java | 24 ++ .../com/bwie/auth/service/AuthService.java | 37 +++ .../auth/service/impl/AuthServiceImpl.java | 244 ++++++++++++++++ bwie-auth/src/main/resources/bootstrap.yml | 25 ++ .../com/bwie/test/PasswordEncoderTest.java | 35 +++ bwie-common/pom.xml | 96 ++++++ .../common/config/ConfirmCallbackConfig.java | 48 +++ .../bwie/common/config/RabbitmqConfig.java | 16 + .../common/config/ReturnsCallbackConfig.java | 40 +++ .../com/bwie/common/constants/Constants.java | 18 ++ .../bwie/common/constants/JwtConstants.java | 29 ++ .../bwie/common/constants/LoginConstants.java | 21 ++ .../constants/MQQueueNameConstants.java | 27 ++ .../bwie/common/constants/RoleConstants.java | 21 ++ .../bwie/common/constants/TokenConstants.java | 24 ++ .../java/com/bwie/common/domain/Article.java | 46 +++ .../java/com/bwie/common/domain/Goods.java | 20 ++ .../com/bwie/common/domain/GoodsType.java | 18 ++ .../java/com/bwie/common/domain/LoginLog.java | 36 +++ .../java/com/bwie/common/domain/SysUser.java | 28 ++ .../common/domain/dto/ArticleSearchDTO.java | 38 +++ .../bwie/common/domain/dto/GoodsQueryDTO.java | 21 ++ .../bwie/common/domain/dto/SendSmsDTO.java | 20 ++ .../common/domain/request/LoginRequest.java | 28 ++ .../common/domain/response/JwtResponse.java | 24 ++ .../common/domain/vo/CountPriceAggVO.java | 24 ++ .../com/bwie/common/domain/vo/GoodsVO.java | 22 ++ .../com/bwie/common/result/PageResult.java | 34 +++ .../java/com/bwie/common/result/Result.java | 76 +++++ .../java/com/bwie/common/utils/JwtUtils.java | 108 +++++++ .../com/bwie/common/utils/StringUtils.java | 68 +++++ .../com/bwie/common/utils/TelSmsUtils.java | 89 ++++++ .../main/resources/META-INF/spring.factories | 4 + bwie-gateway/pom.xml | 54 ++++ .../com/bwie/gateway/GatewayApplication.java | 19 ++ .../gateway/config/IgnoreWhitesConfig.java | 35 +++ .../com/bwie/gateway/filters/AuthFilter.java | 104 +++++++ .../com/bwie/gateway/filters/LogFilter.java | 29 ++ .../com/bwie/gateway/utils/GatewayUtils.java | 102 +++++++ bwie-gateway/src/main/resources/bootstrap.yml | 30 ++ bwie-modules/bwie-es/pom.xml | 30 ++ .../main/java/com/bwie/es/ESApplication.java | 23 ++ .../es/config/InitRestHighLevelClient.java | 35 +++ .../bwie/es/consumer/AddGoodsConsumer.java | 68 +++++ .../bwie/es/cotroller/ArticleController.java | 157 ++++++++++ .../com/bwie/es/remote/GoodsFeignService.java | 26 ++ .../com/bwie/es/service/ArticleService.java | 54 ++++ .../com/bwie/es/service/GoodsService.java | 23 ++ .../es/service/impl/ArticleServiceImpl.java | 274 ++++++++++++++++++ .../es/service/impl/GoodsServiceImpl.java | 137 +++++++++ .../main/java/com/bwie/es/sync/SyncGoods.java | 48 +++ .../java/com/bwie/es/sync/SyncGoods2.java | 50 ++++ .../bwie-es/src/main/resources/bootstrap.yml | 34 +++ bwie-modules/bwie-goods/pom.xml | 50 ++++ .../java/com/bwie/goods/GoodsApplication.java | 19 ++ .../goods/controller/GoodsController.java | 64 ++++ .../com/bwie/goods/mapper/GoodsMapper.java | 32 ++ .../com/bwie/goods/service/GoodsService.java | 30 ++ .../goods/service/impl/GoodsServiceImpl.java | 99 +++++++ .../src/main/resources/bootstrap.yml | 29 ++ .../src/main/resources/mapper/GoodsMapper.xml | 29 ++ bwie-modules/bwie-kafka/pom.xml | 30 ++ .../java/com/bwie/kafka/KafkaApplication.java | 19 ++ .../kafka/config/KafkaConsumerConfig.java | 108 +++++++ .../kafka/config/KafkaProviderConfig.java | 84 ++++++ .../kafka/config/KafkaSendResultHandler.java | 38 +++ .../config/MyKafkaListenerErrorHandler.java | 34 +++ .../consumer/HelloWorldKafkaConsumer.java | 40 +++ .../consumer/KafkaConsumerQuickStart.java | 46 +++ .../controller/HelloWorldKafkaController.java | 63 ++++ .../producer/KafkaProducerQuickStart.java | 69 +++++ .../src/main/resources/bootstrap.yml | 102 +++++++ bwie-modules/bwie-rabbitmq/pom.xml | 35 +++ .../java/com/bwie/mq/RabbitMQApplication.java | 32 ++ .../bwie/mq/config/ConfirmCallbackConfig.java | 48 +++ .../com/bwie/mq/config/RabbitmqConfig.java | 15 + .../bwie/mq/config/ReturnsCallbackConfig.java | 40 +++ .../bwie/mq/consumer/HelloWorldConsumer.java | 27 ++ .../mq/consumer/MessageConverterConsumer.java | 69 +++++ .../mq/consumer/PublishSubscribeConsumer.java | 37 +++ .../com/bwie/mq/consumer/RoutingConsumer.java | 42 +++ .../com/bwie/mq/consumer/TopicConsumer.java | 34 +++ .../bwie/mq/consumer/WorkQueuesConsumer.java | 31 ++ .../bwie/mq/producer/RabbitMQController.java | 111 +++++++ .../src/main/resources/bootstrap.yml | 45 +++ bwie-modules/bwie-rabbitmq/笔记.md | 79 +++++ bwie-modules/bwie-sms/pom.xml | 25 ++ .../java/com/bwie/sms/SmsApplication.java | 19 ++ .../sms/consumer/SendSmsQueueConsumer.java | 77 +++++ .../bwie-sms/src/main/resources/bootstrap.yml | 30 ++ bwie-modules/bwie-system/pom.xml | 50 ++++ .../com/bwie/system/SystemApplication.java | 19 ++ .../system/controller/LoginLogController.java | 16 + .../system/controller/SysUserController.java | 48 +++ .../com/bwie/system/mapper/SysUserMapper.java | 21 ++ .../bwie/system/service/SysUserService.java | 18 ++ .../service/impl/SysUserServiceImpl.java | 25 ++ .../src/main/resources/bootstrap.yml | 30 ++ .../main/resources/mapper/SysUserMapper.xml | 19 ++ bwie-modules/pom.xml | 29 ++ bwie-modules/src/main/java/com/bwie/Main.java | 13 + bwie-rabbit/pom.xml | 35 +++ .../com/bwie/rabbit/RabbitApplication.java | 19 ++ .../bwie/rabbit/config/RabbitAdminConfig.java | 44 +++ .../rabbit/consumer/DelayedQueueConsumer.java | 23 ++ .../rabbit/consumer/TTLQueueConsumer.java | 23 ++ .../rabbit/controller/HelloController.java | 51 ++++ .../java/com/bwie/rabbit/utils/DLXQueue.java | 81 ++++++ .../com/bwie/rabbit/utils/DelayedQueue.java | 85 ++++++ .../java/com/bwie/rabbit/utils/TtlQueue.java | 70 +++++ bwie-rabbit/src/main/resources/bootstrap.yml | 38 +++ 116 files changed, 5557 insertions(+) create mode 100644 bwie-auth/pom.xml create mode 100644 bwie-auth/src/main/java/com/bwie/auth/AuthApplication.java create mode 100644 bwie-auth/src/main/java/com/bwie/auth/consumer/LoginLogQueueConsumer.java create mode 100644 bwie-auth/src/main/java/com/bwie/auth/consumer/WebsiteStatsConsumer.java create mode 100644 bwie-auth/src/main/java/com/bwie/auth/controller/AuthController.java create mode 100644 bwie-auth/src/main/java/com/bwie/auth/feign/SystemFeignService.java create mode 100644 bwie-auth/src/main/java/com/bwie/auth/service/AuthService.java create mode 100644 bwie-auth/src/main/java/com/bwie/auth/service/impl/AuthServiceImpl.java create mode 100644 bwie-auth/src/main/resources/bootstrap.yml create mode 100644 bwie-auth/src/test/java/com/bwie/test/PasswordEncoderTest.java create mode 100644 bwie-common/pom.xml create mode 100644 bwie-common/src/main/java/com/bwie/common/config/ConfirmCallbackConfig.java create mode 100644 bwie-common/src/main/java/com/bwie/common/config/RabbitmqConfig.java create mode 100644 bwie-common/src/main/java/com/bwie/common/config/ReturnsCallbackConfig.java create mode 100644 bwie-common/src/main/java/com/bwie/common/constants/Constants.java create mode 100644 bwie-common/src/main/java/com/bwie/common/constants/JwtConstants.java create mode 100644 bwie-common/src/main/java/com/bwie/common/constants/LoginConstants.java create mode 100644 bwie-common/src/main/java/com/bwie/common/constants/MQQueueNameConstants.java create mode 100644 bwie-common/src/main/java/com/bwie/common/constants/RoleConstants.java create mode 100644 bwie-common/src/main/java/com/bwie/common/constants/TokenConstants.java create mode 100644 bwie-common/src/main/java/com/bwie/common/domain/Article.java create mode 100644 bwie-common/src/main/java/com/bwie/common/domain/Goods.java create mode 100644 bwie-common/src/main/java/com/bwie/common/domain/GoodsType.java create mode 100644 bwie-common/src/main/java/com/bwie/common/domain/LoginLog.java create mode 100644 bwie-common/src/main/java/com/bwie/common/domain/SysUser.java create mode 100644 bwie-common/src/main/java/com/bwie/common/domain/dto/ArticleSearchDTO.java create mode 100644 bwie-common/src/main/java/com/bwie/common/domain/dto/GoodsQueryDTO.java create mode 100644 bwie-common/src/main/java/com/bwie/common/domain/dto/SendSmsDTO.java create mode 100644 bwie-common/src/main/java/com/bwie/common/domain/request/LoginRequest.java create mode 100644 bwie-common/src/main/java/com/bwie/common/domain/response/JwtResponse.java create mode 100644 bwie-common/src/main/java/com/bwie/common/domain/vo/CountPriceAggVO.java create mode 100644 bwie-common/src/main/java/com/bwie/common/domain/vo/GoodsVO.java create mode 100644 bwie-common/src/main/java/com/bwie/common/result/PageResult.java create mode 100644 bwie-common/src/main/java/com/bwie/common/result/Result.java create mode 100644 bwie-common/src/main/java/com/bwie/common/utils/JwtUtils.java create mode 100644 bwie-common/src/main/java/com/bwie/common/utils/StringUtils.java create mode 100644 bwie-common/src/main/java/com/bwie/common/utils/TelSmsUtils.java create mode 100644 bwie-common/src/main/resources/META-INF/spring.factories create mode 100644 bwie-gateway/pom.xml create mode 100644 bwie-gateway/src/main/java/com/bwie/gateway/GatewayApplication.java create mode 100644 bwie-gateway/src/main/java/com/bwie/gateway/config/IgnoreWhitesConfig.java create mode 100644 bwie-gateway/src/main/java/com/bwie/gateway/filters/AuthFilter.java create mode 100644 bwie-gateway/src/main/java/com/bwie/gateway/filters/LogFilter.java create mode 100644 bwie-gateway/src/main/java/com/bwie/gateway/utils/GatewayUtils.java create mode 100644 bwie-gateway/src/main/resources/bootstrap.yml create mode 100644 bwie-modules/bwie-es/pom.xml create mode 100644 bwie-modules/bwie-es/src/main/java/com/bwie/es/ESApplication.java create mode 100644 bwie-modules/bwie-es/src/main/java/com/bwie/es/config/InitRestHighLevelClient.java create mode 100644 bwie-modules/bwie-es/src/main/java/com/bwie/es/consumer/AddGoodsConsumer.java create mode 100644 bwie-modules/bwie-es/src/main/java/com/bwie/es/cotroller/ArticleController.java create mode 100644 bwie-modules/bwie-es/src/main/java/com/bwie/es/remote/GoodsFeignService.java create mode 100644 bwie-modules/bwie-es/src/main/java/com/bwie/es/service/ArticleService.java create mode 100644 bwie-modules/bwie-es/src/main/java/com/bwie/es/service/GoodsService.java create mode 100644 bwie-modules/bwie-es/src/main/java/com/bwie/es/service/impl/ArticleServiceImpl.java create mode 100644 bwie-modules/bwie-es/src/main/java/com/bwie/es/service/impl/GoodsServiceImpl.java create mode 100644 bwie-modules/bwie-es/src/main/java/com/bwie/es/sync/SyncGoods.java create mode 100644 bwie-modules/bwie-es/src/main/java/com/bwie/es/sync/SyncGoods2.java create mode 100644 bwie-modules/bwie-es/src/main/resources/bootstrap.yml create mode 100644 bwie-modules/bwie-goods/pom.xml create mode 100644 bwie-modules/bwie-goods/src/main/java/com/bwie/goods/GoodsApplication.java create mode 100644 bwie-modules/bwie-goods/src/main/java/com/bwie/goods/controller/GoodsController.java create mode 100644 bwie-modules/bwie-goods/src/main/java/com/bwie/goods/mapper/GoodsMapper.java create mode 100644 bwie-modules/bwie-goods/src/main/java/com/bwie/goods/service/GoodsService.java create mode 100644 bwie-modules/bwie-goods/src/main/java/com/bwie/goods/service/impl/GoodsServiceImpl.java create mode 100644 bwie-modules/bwie-goods/src/main/resources/bootstrap.yml create mode 100644 bwie-modules/bwie-goods/src/main/resources/mapper/GoodsMapper.xml create mode 100644 bwie-modules/bwie-kafka/pom.xml create mode 100644 bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/KafkaApplication.java create mode 100644 bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/KafkaConsumerConfig.java create mode 100644 bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/KafkaProviderConfig.java create mode 100644 bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/KafkaSendResultHandler.java create mode 100644 bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/MyKafkaListenerErrorHandler.java create mode 100644 bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/consumer/HelloWorldKafkaConsumer.java create mode 100644 bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/consumer/KafkaConsumerQuickStart.java create mode 100644 bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/controller/HelloWorldKafkaController.java create mode 100644 bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/producer/KafkaProducerQuickStart.java create mode 100644 bwie-modules/bwie-kafka/src/main/resources/bootstrap.yml create mode 100644 bwie-modules/bwie-rabbitmq/pom.xml create mode 100644 bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/RabbitMQApplication.java create mode 100644 bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/config/ConfirmCallbackConfig.java create mode 100644 bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/config/RabbitmqConfig.java create mode 100644 bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/config/ReturnsCallbackConfig.java create mode 100644 bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/HelloWorldConsumer.java create mode 100644 bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/MessageConverterConsumer.java create mode 100644 bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/PublishSubscribeConsumer.java create mode 100644 bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/RoutingConsumer.java create mode 100644 bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/TopicConsumer.java create mode 100644 bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/WorkQueuesConsumer.java create mode 100644 bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/producer/RabbitMQController.java create mode 100644 bwie-modules/bwie-rabbitmq/src/main/resources/bootstrap.yml create mode 100644 bwie-modules/bwie-rabbitmq/笔记.md create mode 100644 bwie-modules/bwie-sms/pom.xml create mode 100644 bwie-modules/bwie-sms/src/main/java/com/bwie/sms/SmsApplication.java create mode 100644 bwie-modules/bwie-sms/src/main/java/com/bwie/sms/consumer/SendSmsQueueConsumer.java create mode 100644 bwie-modules/bwie-sms/src/main/resources/bootstrap.yml create mode 100644 bwie-modules/bwie-system/pom.xml create mode 100644 bwie-modules/bwie-system/src/main/java/com/bwie/system/SystemApplication.java create mode 100644 bwie-modules/bwie-system/src/main/java/com/bwie/system/controller/LoginLogController.java create mode 100644 bwie-modules/bwie-system/src/main/java/com/bwie/system/controller/SysUserController.java create mode 100644 bwie-modules/bwie-system/src/main/java/com/bwie/system/mapper/SysUserMapper.java create mode 100644 bwie-modules/bwie-system/src/main/java/com/bwie/system/service/SysUserService.java create mode 100644 bwie-modules/bwie-system/src/main/java/com/bwie/system/service/impl/SysUserServiceImpl.java create mode 100644 bwie-modules/bwie-system/src/main/resources/bootstrap.yml create mode 100644 bwie-modules/bwie-system/src/main/resources/mapper/SysUserMapper.xml create mode 100644 bwie-modules/pom.xml create mode 100644 bwie-modules/src/main/java/com/bwie/Main.java create mode 100644 bwie-rabbit/pom.xml create mode 100644 bwie-rabbit/src/main/java/com/bwie/rabbit/RabbitApplication.java create mode 100644 bwie-rabbit/src/main/java/com/bwie/rabbit/config/RabbitAdminConfig.java create mode 100644 bwie-rabbit/src/main/java/com/bwie/rabbit/consumer/DelayedQueueConsumer.java create mode 100644 bwie-rabbit/src/main/java/com/bwie/rabbit/consumer/TTLQueueConsumer.java create mode 100644 bwie-rabbit/src/main/java/com/bwie/rabbit/controller/HelloController.java create mode 100644 bwie-rabbit/src/main/java/com/bwie/rabbit/utils/DLXQueue.java create mode 100644 bwie-rabbit/src/main/java/com/bwie/rabbit/utils/DelayedQueue.java create mode 100644 bwie-rabbit/src/main/java/com/bwie/rabbit/utils/TtlQueue.java create mode 100644 bwie-rabbit/src/main/resources/bootstrap.yml diff --git a/bwie-auth/pom.xml b/bwie-auth/pom.xml new file mode 100644 index 0000000..ef96fdf --- /dev/null +++ b/bwie-auth/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + com.bwie + bwie-1016 + 1.0-SNAPSHOT + + + bwie-auth + + + 8 + 8 + UTF-8 + + + + + + com.bwie + bwie-common + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + + + + + ${project.artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + diff --git a/bwie-auth/src/main/java/com/bwie/auth/AuthApplication.java b/bwie-auth/src/main/java/com/bwie/auth/AuthApplication.java new file mode 100644 index 0000000..51a5467 --- /dev/null +++ b/bwie-auth/src/main/java/com/bwie/auth/AuthApplication.java @@ -0,0 +1,28 @@ +package com.bwie.auth; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.context.annotation.Bean; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/16 + */ +@SpringBootApplication +@EnableFeignClients +public class AuthApplication { + + public static void main(String[] args) { + SpringApplication.run(AuthApplication.class); + } + + @Bean + public BCryptPasswordEncoder bCryptPasswordEncoder() { + return new BCryptPasswordEncoder(); + } + +} diff --git a/bwie-auth/src/main/java/com/bwie/auth/consumer/LoginLogQueueConsumer.java b/bwie-auth/src/main/java/com/bwie/auth/consumer/LoginLogQueueConsumer.java new file mode 100644 index 0000000..ad4d79a --- /dev/null +++ b/bwie-auth/src/main/java/com/bwie/auth/consumer/LoginLogQueueConsumer.java @@ -0,0 +1,52 @@ +package com.bwie.auth.consumer; + +import com.bwie.common.constants.MQQueueNameConstants; +import com.bwie.common.domain.LoginLog; +import com.rabbitmq.client.Channel; +import lombok.extern.log4j.Log4j2; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/25 + */ +@Component +@Log4j2 +public class LoginLogQueueConsumer { + + @Autowired + private RedisTemplate redisTemplate; + + @RabbitListener(queuesToDeclare = {@Queue(MQQueueNameConstants.LOGIN_LOG_QUEUE_NAME)}) + public void loginLogQueueConsumer(Message message, LoginLog loginLog, Channel channel) { + log.info(""); + String messageId = message.getMessageProperties().getMessageId(); + try { + Long add = redisTemplate.opsForSet().add(MQQueueNameConstants.LOGIN_LOG_QUEUE_NAME, messageId); + if (add == 1) { + // 正常消费 远程调用 + // 手动 确认 + channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); + log.info(""); + } + } catch (Exception e) { + log.error(""); + redisTemplate.opsForSet().remove(MQQueueNameConstants.LOGIN_LOG_QUEUE_NAME, messageId); + try { + channel.basicReject(message.getMessageProperties().getDeliveryTag(), true); + } catch (IOException ex) { + log.error(""); + } + } + } + +} diff --git a/bwie-auth/src/main/java/com/bwie/auth/consumer/WebsiteStatsConsumer.java b/bwie-auth/src/main/java/com/bwie/auth/consumer/WebsiteStatsConsumer.java new file mode 100644 index 0000000..07cdf08 --- /dev/null +++ b/bwie-auth/src/main/java/com/bwie/auth/consumer/WebsiteStatsConsumer.java @@ -0,0 +1,57 @@ +package com.bwie.auth.consumer; + +import com.bwie.common.constants.MQQueueNameConstants; +import com.rabbitmq.client.Channel; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * @ClassName: + * @Description: 统计网站人次 队列消费者 + * @Author: zhuwenqiang + * @Date: 2023/10/31 + */ +@Component +public class WebsiteStatsConsumer { + + @Autowired + private RedisTemplate redisTemplate; + + @RabbitListener(queuesToDeclare = {@Queue(MQQueueNameConstants.WEBSITE_STATS_QUEUE)}) + public void websiteStatsConsumer(Message message, String msg, Channel channel) { + // 获取消息id + String messageId = message.getMessageProperties().getMessageId(); + try { + Long count = redisTemplate.opsForSet().add("website_stats_queue", messageId); + if (count == 1) { + // 统计每日人次 访问次数 + 1 + // 获取当前日期字符串 20231031 + SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); + String dateStr = format.format(new Date()); +// if (!redisTemplate.hasKey(dateStr)) { + // redis 自增 每次 + 1 重复登录不算 + redisTemplate.opsForValue().increment(dateStr); +// } + // 消息确认 + channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); + } + } catch (Exception e) { + redisTemplate.opsForSet().remove("website_stats_queue", messageId); + try { + channel.basicReject(message.getMessageProperties().getDeliveryTag(), true); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + +} diff --git a/bwie-auth/src/main/java/com/bwie/auth/controller/AuthController.java b/bwie-auth/src/main/java/com/bwie/auth/controller/AuthController.java new file mode 100644 index 0000000..a2d44b2 --- /dev/null +++ b/bwie-auth/src/main/java/com/bwie/auth/controller/AuthController.java @@ -0,0 +1,86 @@ +package com.bwie.auth.controller; + +import com.alibaba.fastjson.JSONObject; +import com.bwie.auth.service.AuthService; +import com.bwie.common.domain.SysUser; +import com.bwie.common.domain.request.LoginRequest; +import com.bwie.common.domain.response.JwtResponse; +import com.bwie.common.result.Result; +import lombok.extern.log4j.Log4j2; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/16 + */ +@RestController +@Log4j2 +public class AuthController { + + @Autowired + private HttpServletRequest request; + + @Autowired + private AuthService authService; + + /** + * 发送短信验证码 + */ + @PostMapping("send/code/{tel}") + public Result sendCode(@PathVariable String tel) { + log.info("功能名称:发送短信验证码,请求URI:{},请求方式:{},请求参数:{}", request.getRequestURI(), + request.getMethod(), tel); + // 发送验证码 + Result result = authService.sendCode(tel); + log.info("功能名称:发送短信验证码,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + /** + * 短信验证码登录 + */ + @PostMapping("login") + public Result login(@RequestBody LoginRequest loginRequest) { + log.info("功能名称:短信验证码登录,请求URI:{},请求方式:{},请求参数:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(loginRequest)); + // 登录 + Result result = authService.login(loginRequest); + log.info("功能名称:短信验证码登录,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + @PostMapping("login2") + public Result login2(@RequestBody LoginRequest loginRequest) { + log.info("功能名称:短信验证码登录,请求URI:{},请求方式:{},请求参数:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(loginRequest)); + // 登录 + Result result = authService.login2(loginRequest); + log.info("功能名称:短信验证码登录,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + /** + * 查询用户信息 + * @return + */ + @GetMapping("user/info") + public Result userInfo() { + log.info("功能名称:查询用户信息,请求URI:{},请求方式:{}", request.getRequestURI(), + request.getMethod()); + SysUser sysUser = authService.userInfo(); + Result result = Result.success(sysUser); + log.info("功能名称:查询用户信息,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + +} diff --git a/bwie-auth/src/main/java/com/bwie/auth/feign/SystemFeignService.java b/bwie-auth/src/main/java/com/bwie/auth/feign/SystemFeignService.java new file mode 100644 index 0000000..d807614 --- /dev/null +++ b/bwie-auth/src/main/java/com/bwie/auth/feign/SystemFeignService.java @@ -0,0 +1,24 @@ +package com.bwie.auth.feign; + +import com.bwie.common.domain.SysUser; +import com.bwie.common.result.Result; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/16 + */ +@FeignClient("bwie-system") +public interface SystemFeignService { + + /** + * 根据手机号查询用户信息 + */ + @GetMapping("sys/user/findByTel/{tel}") + public Result findByTel(@PathVariable String tel); + +} diff --git a/bwie-auth/src/main/java/com/bwie/auth/service/AuthService.java b/bwie-auth/src/main/java/com/bwie/auth/service/AuthService.java new file mode 100644 index 0000000..a41ac5e --- /dev/null +++ b/bwie-auth/src/main/java/com/bwie/auth/service/AuthService.java @@ -0,0 +1,37 @@ +package com.bwie.auth.service; + +import com.bwie.common.domain.SysUser; +import com.bwie.common.domain.request.LoginRequest; +import com.bwie.common.domain.response.JwtResponse; +import com.bwie.common.result.Result; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/16 + */ +public interface AuthService { + /** + * 发送短信验证码 + * @param tel + * @return + */ + Result sendCode(String tel); + + /** + * 短信验证码登录 + * @param loginRequest + * @return + */ + Result login(LoginRequest loginRequest); + + /** + * + * @return + */ + SysUser userInfo(); + + + Result login2(LoginRequest loginRequest); +} diff --git a/bwie-auth/src/main/java/com/bwie/auth/service/impl/AuthServiceImpl.java b/bwie-auth/src/main/java/com/bwie/auth/service/impl/AuthServiceImpl.java new file mode 100644 index 0000000..6650174 --- /dev/null +++ b/bwie-auth/src/main/java/com/bwie/auth/service/impl/AuthServiceImpl.java @@ -0,0 +1,244 @@ +package com.bwie.auth.service.impl; + +import cn.hutool.core.codec.Base64; +import cn.hutool.core.util.RandomUtil; +import com.alibaba.fastjson.JSONObject; +import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody; +import com.bwie.auth.feign.SystemFeignService; +import com.bwie.auth.service.AuthService; +import com.bwie.common.constants.JwtConstants; +import com.bwie.common.constants.LoginConstants; +import com.bwie.common.constants.MQQueueNameConstants; +import com.bwie.common.constants.TokenConstants; +import com.bwie.common.domain.LoginLog; +import com.bwie.common.domain.SysUser; +import com.bwie.common.domain.dto.SendSmsDTO; +import com.bwie.common.domain.request.LoginRequest; +import com.bwie.common.domain.response.JwtResponse; +import com.bwie.common.result.Result; +import com.bwie.common.utils.JwtUtils; +import com.bwie.common.utils.StringUtils; +import com.bwie.common.utils.TelSmsUtils; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/16 + */ +@Service +public class AuthServiceImpl implements AuthService { + + @Autowired + private SystemFeignService systemFeignService; + + @Autowired + private RedisTemplate redisTemplate; + + @Autowired + private HttpServletRequest request; + + @Autowired + private RabbitTemplate rabbitTemplate; + + @Autowired + private BCryptPasswordEncoder bCryptPasswordEncoder; + + @Override + public Result sendCode(String tel) { + // 验证手机号的格式 + if (!validateTel(tel)) { + return Result.error("手机号格式不正确!"); + } + // 验证码该手机是否属于系统用户 远程调用 springcloud openFeign (RPC remote producer call) + Result byTel = systemFeignService.findByTel(tel); + SysUser sysUser = byTel.getData(); + if (sysUser == null) { + return Result.error("手机号不是系统用户!"); + } + String code = ""; + if (redisTemplate.hasKey(tel)) { + code = redisTemplate.opsForValue().get(tel); + } else { + // 生成验证码 + code = RandomUtil.randomNumbers(4); + } + // 存储验证码 + redisTemplate.opsForValue().set(tel, code, 5, TimeUnit.MINUTES); + SendSmsDTO sendSmsDTO = new SendSmsDTO(); + sendSmsDTO.setMobile(tel); + sendSmsDTO.setKey("code"); + sendSmsDTO.setValue(code); + // 发送消息到 短信队列 + rabbitTemplate.convertAndSend("send_sms_queue", sendSmsDTO, message -> { + message.getMessageProperties().setMessageId(UUID.randomUUID().toString()); + return message; + }); + return Result.success(); + } + + @Override + public Result login(LoginRequest loginRequest) { + // 验证 参数 + if (StringUtils.isAllBlank(loginRequest.getTel(), loginRequest.getCode())) { + addLoginLog(loginRequest.getTel(), LoginConstants.LOGIN_FAIL, "手机号或者验证码不能为空!"); + return Result.error("手机号或者验证码不能为空!"); + } + // 根据手机号查询 + Result byTel = systemFeignService.findByTel(loginRequest.getTel()); + SysUser sysUser = byTel.getData(); + if (sysUser == null) { + addLoginLog(loginRequest.getTel(), LoginConstants.LOGIN_FAIL, "手机号不存在!"); + return Result.error("手机号不存在!"); + } + // 判断验证码 + String code = redisTemplate.opsForValue().get(loginRequest.getTel()); + if (StringUtils.isBlank(code)) { + addLoginLog(loginRequest.getTel(), LoginConstants.LOGIN_FAIL, "请先发送短信验证码!"); + return Result.error("请先发送短信验证码!"); + } + if (!code.equals(loginRequest.getCode())) { + addLoginLog(loginRequest.getTel(), LoginConstants.LOGIN_FAIL, "验证码错误!"); + return Result.error("验证码错误!"); + } + // 登录成功 + addLoginLog(loginRequest.getTel(), LoginConstants.LOGIN_SUCCESS, "登录成功!"); + + // 使用 redis 统计人次 + rabbitTemplate.convertAndSend(MQQueueNameConstants.WEBSITE_STATS_QUEUE, "1", message -> { + message.getMessageProperties().setMessageId(UUID.randomUUID().toString()); + return message; + }); + + // 登录成功 生成 token + // 数据 将什么数据放入 token -> 根据token 解析出原来放入的数据 【对应相应的用户】 + Map claims = new HashMap<>(); + String userKey = UUID.randomUUID().toString().replaceAll("-", ""); + claims.put(JwtConstants.USER_KEY, userKey); + String token = JwtUtils.createToken(claims); + // 存储用户的信息 30Min + // 设置用户的登录时间 + sysUser.setLoginDate(new Date()); + redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY + userKey, JSONObject.toJSONString(sysUser), 30, TimeUnit.MINUTES); + // 返回响应数据 + JwtResponse jwtResponse = new JwtResponse(); + jwtResponse.setToken(token); + jwtResponse.setExpireTime("30MIN"); + return Result.success(jwtResponse); + } + + /** + * 异步 记录登录日志记录 + */ + private void addLoginLog(String username, int isOk, String promptInfo) { + LoginLog loginLog = new LoginLog(); + loginLog.setLoginTime(new Date()); + loginLog.setPromptInfo(promptInfo); + loginLog.setIsOk(isOk); + loginLog.setUsername(username); + rabbitTemplate.convertAndSend(MQQueueNameConstants.LOGIN_LOG_QUEUE_NAME, loginLog, message -> { + // 设置消息的id + message.getMessageProperties().setMessageId(UUID.randomUUID().toString()); + return message; + }); + } + + + @Override + public SysUser userInfo() { + String token = request.getHeader(TokenConstants.TOKEN); + String userKey = JwtUtils.getUserKey(token); + String userJson = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey); + return JSONObject.parseObject(userJson, SysUser.class); + } + + @Override + public Result login2(LoginRequest loginRequest) { + // 验证 参数 + if (StringUtils.isAllBlank(loginRequest.getTel(), loginRequest.getPassword())) { + addLoginLog(loginRequest.getTel(), LoginConstants.LOGIN_FAIL, "手机号或者验证码不能为空!"); + return Result.error("手机号或者验证码不能为空!"); + } + // 根据手机号查询 + Result byTel = systemFeignService.findByTel(loginRequest.getTel()); + SysUser sysUser = byTel.getData(); + if (sysUser == null) { + addLoginLog(loginRequest.getTel(), LoginConstants.LOGIN_FAIL, "手机号不存在!"); + return Result.error("手机号不存在!"); + } + // 判断验证码 第一个参数 明文 原始密码 用户输入的 第二个: 密码 数据查询的出来的 加密的 + boolean matches = bCryptPasswordEncoder.matches(loginRequest.getPassword(), sysUser.getPassword()); + if (!matches) { + return Result.error("密码错误!"); + } + // 登录成功 + addLoginLog(loginRequest.getTel(), LoginConstants.LOGIN_SUCCESS, "登录成功!"); + + // 登录成功 生成 token + // 数据 将什么数据放入 token -> 根据token 解析出原来放入的数据 【对应相应的用户】 + Map claims = new HashMap<>(); + String userKey = UUID.randomUUID().toString().replaceAll("-", ""); + claims.put(JwtConstants.USER_KEY, userKey); + String token = JwtUtils.createToken(claims); + // 存储用户的信息 30Min + // 设置用户的登录时间 + sysUser.setLoginDate(new Date()); + redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY + userKey, JSONObject.toJSONString(sysUser), 30, TimeUnit.MINUTES); + // 返回响应数据 + JwtResponse jwtResponse = new JwtResponse(); + jwtResponse.setToken(token); + jwtResponse.setExpireTime("30MIN"); + return Result.success(jwtResponse); + } + + /** + * 验证手机号格式 + * + * @param tel + * @return + */ + private boolean validateTel(String tel) { + // 定义正则表达式 + Pattern compile = + Pattern.compile("^(?:(?:\\+|00)86)?1(?:(?:3[\\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\\d])|(?:9[1|8|9]))\\d{8}$"); + return compile.matcher(tel).matches(); + } + + + public static void main(String[] args) { + + String str = "{\n" + + " \"alg\": \"HS256\",\n" + + " \"typ\": \"JWT\"\n" + + "}"; + +// for (int i = 0; i < 10; i++) { + String js = Base64.encode(str); + System.out.println(js); +// } + + String str2 = "ewogICJhbGciOiAiSFMyNTYiLAogICJ0eXAiOiAiSldUIgp9"; + String encode = Base64.decodeStr(str2); + System.out.println(encode); + + String s = UUID.randomUUID().toString(); + String s2 = UUID.randomUUID().toString().replaceAll("-", ""); + System.out.println(s); + System.out.println(s2); + } + + +} diff --git a/bwie-auth/src/main/resources/bootstrap.yml b/bwie-auth/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..4eaa511 --- /dev/null +++ b/bwie-auth/src/main/resources/bootstrap.yml @@ -0,0 +1,25 @@ +server: + port: 9001 +spring: + main: + allow-circular-references: true # 允许循环依赖 + jackson: # json 序列化 和 返序列化 转换 + date-format: yyyy-MM-dd HH:mm:ss + time-zone: GMT+8 + application: + name: bwie-auth + profiles: + active: dev + # 配置nacos + cloud: + nacos: + discovery: + server-addr: 123.249.113.136:8848 + config: + server-addr: 123.249.113.136:8848 + namespace: a9b66e92-e507-47ba-9674-6f939f793aca + file-extension: yml + # 共享配置 application-dev.yml + shared-configs: + - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} + diff --git a/bwie-auth/src/test/java/com/bwie/test/PasswordEncoderTest.java b/bwie-auth/src/test/java/com/bwie/test/PasswordEncoderTest.java new file mode 100644 index 0000000..901421f --- /dev/null +++ b/bwie-auth/src/test/java/com/bwie/test/PasswordEncoderTest.java @@ -0,0 +1,35 @@ +package com.bwie.test; + +import com.alibaba.nacos.common.utils.MD5Utils; +import com.bwie.auth.AuthApplication; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/31 + */ +@SpringBootTest(classes = AuthApplication.class) +public class PasswordEncoderTest { + + @Autowired + private BCryptPasswordEncoder bCryptPasswordEncoder; + + @Test + public void testPassEncode() { + String pwd = "123"; + // 加密方法 + for (int i = 0; i < 10; i++) { + // 加密方法 + String encode = bCryptPasswordEncoder.encode(pwd); + System.out.println(encode); + } + // 匹配 方法 + } + + +} diff --git a/bwie-common/pom.xml b/bwie-common/pom.xml new file mode 100644 index 0000000..8fe5dcd --- /dev/null +++ b/bwie-common/pom.xml @@ -0,0 +1,96 @@ + + + 4.0.0 + + com.bwie + bwie-1016 + 1.0-SNAPSHOT + + + bwie-common + + + + + org.springframework.cloud + spring-cloud-starter-bootstrap + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sentinel + + + + org.springframework.cloud + spring-cloud-starter-loadbalancer + + + + org.springframework.cloud + spring-cloud-starter-openfeign + + + + io.jsonwebtoken + jjwt + + + + com.alibaba + fastjson + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + org.springframework.boot + spring-boot-starter-validation + + + + org.apache.commons + commons-lang3 + + + + org.projectlombok + lombok + + + + cn.hutool + hutool-all + 5.8.3 + + + + com.aliyun + dysmsapi20170525 + 2.0.1 + + + + org.springframework.boot + spring-boot-starter-amqp + + + + + + diff --git a/bwie-common/src/main/java/com/bwie/common/config/ConfirmCallbackConfig.java b/bwie-common/src/main/java/com/bwie/common/config/ConfirmCallbackConfig.java new file mode 100644 index 0000000..6970292 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/config/ConfirmCallbackConfig.java @@ -0,0 +1,48 @@ +package com.bwie.common.config; + +import org.springframework.amqp.rabbit.connection.CorrelationData; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +/** + * @ClassName: + * @Description: 消息发送到 broker的确认 重写 confirm 方法 + * @Author: zhuwenqiang + * @Date: 2023/10/23 + */ +@Component +public class ConfirmCallbackConfig implements RabbitTemplate.ConfirmCallback { + + @Autowired + private RabbitTemplate rabbitTemplate; + + /** + * 当前类被初始化的时候执行的方法 + * + */ + @PostConstruct + public void init() { + // 设置 rabbitTemplate 的消息发送到交换机确认 + rabbitTemplate.setConfirmCallback(this); + } + + /** + * 消息发送到交换机 无论成功或者失败 都会执行 + * + * @param correlationData correlation data for the callback. + * @param ack true for ack, false for nack true 成功 false 失败 + * @param cause An optional cause, for nack, when available, otherwise null. + */ + @Override + public void confirm(CorrelationData correlationData, boolean ack, String cause) { + if (ack) { + System.out.println("消息发送到broker成功!"); + } else { + System.out.println("消息发送到broker失败,失败的原因是:" + cause); + } + } + +} diff --git a/bwie-common/src/main/java/com/bwie/common/config/RabbitmqConfig.java b/bwie-common/src/main/java/com/bwie/common/config/RabbitmqConfig.java new file mode 100644 index 0000000..335f160 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/config/RabbitmqConfig.java @@ -0,0 +1,16 @@ +package com.bwie.common.config; + +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; + +@Configuration +public class RabbitmqConfig { + // 消息转换配置 SimpleMessageConverter String byte[] serializable + @Bean + public MessageConverter jsonMessageConverter() { + return new Jackson2JsonMessageConverter(); + } + +} diff --git a/bwie-common/src/main/java/com/bwie/common/config/ReturnsCallbackConfig.java b/bwie-common/src/main/java/com/bwie/common/config/ReturnsCallbackConfig.java new file mode 100644 index 0000000..e1522bf --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/config/ReturnsCallbackConfig.java @@ -0,0 +1,40 @@ +package com.bwie.common.config; + +import org.springframework.amqp.core.ReturnedMessage; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +/** + * @ClassName: + * @Description: 消息发送到队列的确认 + * @Author: zhuwenqiang + * @Date: 2023/10/23 + */ +@Component +public class ReturnsCallbackConfig implements RabbitTemplate.ReturnsCallback { + + @Autowired + private RabbitTemplate rabbitTemplate; + + @PostConstruct + public void init() { + rabbitTemplate.setReturnsCallback(this); + } + + /** + * 只有发送到队列失败才会执行 + * + * @param returnedMessage the returned message and metadata. + */ + @Override + public void returnedMessage(ReturnedMessage returnedMessage) { + System.out.println("消息" + returnedMessage.getMessage().toString() + + "被交换机" + returnedMessage.getExchange() + "回退!" + + "退回原因为:" + returnedMessage.getReplyText()); + // TODO 补偿 可以再发 做日志记录 + } + +} diff --git a/bwie-common/src/main/java/com/bwie/common/constants/Constants.java b/bwie-common/src/main/java/com/bwie/common/constants/Constants.java new file mode 100644 index 0000000..2fdc9fe --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/constants/Constants.java @@ -0,0 +1,18 @@ +package com.bwie.common.constants; + +/** + * @description: 系统常量 + * @author DongZl + */ +public class Constants { + /** + * 成功标记 + */ + public static final Integer SUCCESS = 200; + public static final String SUCCESS_MSG = "操作成功"; + /** + * 失败标记 + */ + public static final Integer ERROR = 500; + public static final String ERROR_MSG = "操作异常"; +} diff --git a/bwie-common/src/main/java/com/bwie/common/constants/JwtConstants.java b/bwie-common/src/main/java/com/bwie/common/constants/JwtConstants.java new file mode 100644 index 0000000..03692c1 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/constants/JwtConstants.java @@ -0,0 +1,29 @@ +package com.bwie.common.constants; + +/** + * @author DongZl + * @description: Jwt常量 + */ +public class JwtConstants { + + /** + * 用户ID字段 + */ + public static final String DETAILS_USER_ID = "user_id"; + + /** + * 用户名字段 + */ + public static final String DETAILS_USERNAME = "username"; + + /** + * 用户标识 + */ + public static final String USER_KEY = "user_key"; + + /** + * 令牌秘钥 + */ + public final static String SECRET = "abcdefghijklmnopqrstuvwxyz"; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/constants/LoginConstants.java b/bwie-common/src/main/java/com/bwie/common/constants/LoginConstants.java new file mode 100644 index 0000000..7763beb --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/constants/LoginConstants.java @@ -0,0 +1,21 @@ +package com.bwie.common.constants; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/25 + */ +public class LoginConstants { + + /** + * 登录成功 + */ + public static final int LOGIN_SUCCESS = 1; + + /** + * 登录失败 + */ + public static final int LOGIN_FAIL = 2; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/constants/MQQueueNameConstants.java b/bwie-common/src/main/java/com/bwie/common/constants/MQQueueNameConstants.java new file mode 100644 index 0000000..4262fb7 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/constants/MQQueueNameConstants.java @@ -0,0 +1,27 @@ +package com.bwie.common.constants; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/25 + */ +public class MQQueueNameConstants { + + /** + * 登录日志队列名称 + */ + public static final String LOGIN_LOG_QUEUE_NAME = "login_log_queue_name"; + + /** + * 添加 + */ + public static final String ADD_GOODS_ES_QUEUE_NAME = "add_goods_es_queue_name"; + + + /** + * 统计网站每日访问人次 + */ + public static final String WEBSITE_STATS_QUEUE = "website_stats_queue"; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/constants/RoleConstants.java b/bwie-common/src/main/java/com/bwie/common/constants/RoleConstants.java new file mode 100644 index 0000000..ff24554 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/constants/RoleConstants.java @@ -0,0 +1,21 @@ +package com.bwie.common.constants; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/18 + */ +public class RoleConstants { + + /** + * 管理员 + */ + public static final int ADMIN = 1; + + /** + * 普通用户 + */ + public static final int ORDINARY_USERS = 2; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/constants/TokenConstants.java b/bwie-common/src/main/java/com/bwie/common/constants/TokenConstants.java new file mode 100644 index 0000000..803e706 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/constants/TokenConstants.java @@ -0,0 +1,24 @@ +package com.bwie.common.constants; + +/** + * @author DongZl + * @description: 令牌常量 + */ +public class TokenConstants { + /** + * 缓存有效期,默认30(分钟) + */ + public final static long EXPIRATION = 30; + /** + * 缓存刷新时间,默认120(分钟) + */ + public final static long REFRESH_TIME = 120; + /** + * 权限缓存前缀 + */ + public final static String LOGIN_TOKEN_KEY = "login_tokens:"; + /** + * token标识 + */ + public static final String TOKEN = "token"; +} diff --git a/bwie-common/src/main/java/com/bwie/common/domain/Article.java b/bwie-common/src/main/java/com/bwie/common/domain/Article.java new file mode 100644 index 0000000..77e1b51 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/domain/Article.java @@ -0,0 +1,46 @@ +package com.bwie.common.domain; + +import lombok.Data; + +import java.util.Date; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/27 + */ +@Data +public class Article { + + /** + * 主键 文档id String + */ + private String id; + + /** + * 标题 + */ + private String title; + + /** + * 作者 + */ + private String author; + + /** + * 地址 + */ + private String address; + + /** + * 价格 + */ + private Double price; + + /** + * 创建时间 + */ + private Date createTime; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/domain/Goods.java b/bwie-common/src/main/java/com/bwie/common/domain/Goods.java new file mode 100644 index 0000000..40154c6 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/domain/Goods.java @@ -0,0 +1,20 @@ +package com.bwie.common.domain; + +import lombok.Data; + +import java.math.BigDecimal; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/18 + */ +@Data +public class Goods { + private Long id; + private String goodsName; + private BigDecimal price; + private Long createBy; + private Long typeId; +} diff --git a/bwie-common/src/main/java/com/bwie/common/domain/GoodsType.java b/bwie-common/src/main/java/com/bwie/common/domain/GoodsType.java new file mode 100644 index 0000000..b86f446 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/domain/GoodsType.java @@ -0,0 +1,18 @@ +package com.bwie.common.domain; + +import lombok.Data; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/18 + */ +@Data +public class GoodsType { + + private Long id; + + private String typeName; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/domain/LoginLog.java b/bwie-common/src/main/java/com/bwie/common/domain/LoginLog.java new file mode 100644 index 0000000..7a42167 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/domain/LoginLog.java @@ -0,0 +1,36 @@ +package com.bwie.common.domain; + +import lombok.Data; + +import java.util.Date; + +/** + * @ClassName: + * @Description: 登录日志实体类 + * @Author: zhuwenqiang + * @Date: 2023/10/25 + */ +@Data +public class LoginLog { + /** + * + */ + private Long id; + /** + * 登录人 + */ + private String username; + /** + * 登录时间 + */ + private Date loginTime; + /** + * 1-成功 2-失败 + */ + private Integer isOk; + /** + * 提示信息 + */ + private String promptInfo; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/domain/SysUser.java b/bwie-common/src/main/java/com/bwie/common/domain/SysUser.java new file mode 100644 index 0000000..3c13479 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/domain/SysUser.java @@ -0,0 +1,28 @@ +package com.bwie.common.domain; + +import lombok.Data; + +import java.io.Serializable; +import java.security.SecureRandom; +import java.util.Date; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/16 + */ +@Data +public class SysUser implements Serializable{ + private Long id; + private String tel; + private String name; + private String username; + private String password; + private String avatar; + private Integer isLock; + private Date lockTime; + private Integer role; + + private Date loginDate; +} diff --git a/bwie-common/src/main/java/com/bwie/common/domain/dto/ArticleSearchDTO.java b/bwie-common/src/main/java/com/bwie/common/domain/dto/ArticleSearchDTO.java new file mode 100644 index 0000000..e278ce2 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/domain/dto/ArticleSearchDTO.java @@ -0,0 +1,38 @@ +package com.bwie.common.domain.dto; + +import lombok.Data; + +import java.util.Date; + +/** + * @ClassName: + * @Description: 文章搜索请求对象 + * @Author: zhuwenqiang + * @Date: 2023/10/28 + */ +@Data +public class ArticleSearchDTO { + + /** + * 文章 标题 + */ + private String title; + + /** + * 作者 + */ + private String author; + + /** + * 创建 区间 + */ + private Date beginDate; + private Date endDate; + + /** + * 分页 + */ + private Integer pageNum = 1; + private Integer pageSize = 2; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/domain/dto/GoodsQueryDTO.java b/bwie-common/src/main/java/com/bwie/common/domain/dto/GoodsQueryDTO.java new file mode 100644 index 0000000..4ccbb8e --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/domain/dto/GoodsQueryDTO.java @@ -0,0 +1,21 @@ +package com.bwie.common.domain.dto; + +import lombok.Data; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/18 + */ +@Data +public class GoodsQueryDTO { + + private String goodsName; + + private Long createBy; + + private Integer pageNum = 1; + private Integer pageSize = 2; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/domain/dto/SendSmsDTO.java b/bwie-common/src/main/java/com/bwie/common/domain/dto/SendSmsDTO.java new file mode 100644 index 0000000..747eab1 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/domain/dto/SendSmsDTO.java @@ -0,0 +1,20 @@ +package com.bwie.common.domain.dto; + +import lombok.Data; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/24 + */ +@Data +public class SendSmsDTO { + + private String mobile; + + private String key; + + private String value; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/domain/request/LoginRequest.java b/bwie-common/src/main/java/com/bwie/common/domain/request/LoginRequest.java new file mode 100644 index 0000000..2c78460 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/domain/request/LoginRequest.java @@ -0,0 +1,28 @@ +package com.bwie.common.domain.request; + +import lombok.Data; + +/** + * @ClassName: + * @Description: 登录请求实体类 + * @Author: zhuwenqiang + * @Date: 2023/10/17 + */ +@Data +public class LoginRequest { + + /** + * 手机号 + */ + private String tel; + + /** + * 验证码 + */ + private String code; + + private String username; + + private String password; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/domain/response/JwtResponse.java b/bwie-common/src/main/java/com/bwie/common/domain/response/JwtResponse.java new file mode 100644 index 0000000..e12c166 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/domain/response/JwtResponse.java @@ -0,0 +1,24 @@ +package com.bwie.common.domain.response; + +import lombok.Data; + +/** + * @ClassName: + * @Description: 登录响应实体类 + * @Author: zhuwenqiang + * @Date: 2023/10/17 + */ +@Data +public class JwtResponse { + + /** + * 令牌 + */ + private String token; + + /** + * 过期时间 + */ + private String expireTime; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/domain/vo/CountPriceAggVO.java b/bwie-common/src/main/java/com/bwie/common/domain/vo/CountPriceAggVO.java new file mode 100644 index 0000000..dd1b113 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/domain/vo/CountPriceAggVO.java @@ -0,0 +1,24 @@ +package com.bwie.common.domain.vo; + +import lombok.Data; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/11/1 + */ +@Data +public class CountPriceAggVO { + + /** + * key 分组的列对应的值 例如: price 1, 2, 5 + */ + private String keyName; + + /** + * 数量 + */ + private Long count; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/domain/vo/GoodsVO.java b/bwie-common/src/main/java/com/bwie/common/domain/vo/GoodsVO.java new file mode 100644 index 0000000..ee704ca --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/domain/vo/GoodsVO.java @@ -0,0 +1,22 @@ +package com.bwie.common.domain.vo; + +import com.bwie.common.domain.Goods; +import lombok.Data; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/18 + */ +@Data +public class GoodsVO extends Goods { + + /** + * + */ + private String typeName; + + private String username; + +} diff --git a/bwie-common/src/main/java/com/bwie/common/result/PageResult.java b/bwie-common/src/main/java/com/bwie/common/result/PageResult.java new file mode 100644 index 0000000..85ecdda --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/result/PageResult.java @@ -0,0 +1,34 @@ +package com.bwie.common.result; + +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * @author DongZl + * @description: 列表返回结果集 + */ +@Data +public class PageResult implements Serializable { + /** + * 总条数 + */ + private long total; + /** + * 结果集合 + */ + private List list; + public PageResult() { + } + public PageResult(long total, List list) { + this.total = total; + this.list = list; + } + public static PageResult toPageResult(long total, List list){ + return new PageResult(total , list); + } + public static Result> toResult(long total, List list){ + return Result.success(PageResult.toPageResult(total,list)); + } +} diff --git a/bwie-common/src/main/java/com/bwie/common/result/Result.java b/bwie-common/src/main/java/com/bwie/common/result/Result.java new file mode 100644 index 0000000..30b1e73 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/result/Result.java @@ -0,0 +1,76 @@ +package com.bwie.common.result; + +import com.bwie.common.constants.Constants; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author DongZl + * @description: 响应信息主体 + */ +@Data +public class Result implements Serializable { + + private static final long serialVersionUID = 1L; + /** + * 成功 + */ + public static final int SUCCESS = Constants.SUCCESS; + /** + * 失败 + */ + public static final int FAIL = Constants.ERROR; + /** + * 返回状态码 + */ + private int code; + /** + * 响应信息 + */ + private String msg; + /** + * 响应数据 + */ + private T data; + + public static Result success() { + return restResult(null, SUCCESS, Constants.SUCCESS_MSG); + } + + public static Result success(T data) { + return restResult(data, SUCCESS, Constants.SUCCESS_MSG); + } + + public static Result success(T data, String msg) { + return restResult(data, SUCCESS, msg); + } + + public static Result error() { + return restResult(null, FAIL, Constants.ERROR_MSG); + } + + public static Result error(String msg) { + return restResult(null, FAIL, msg); + } + + public static Result error(T data) { + return restResult(data, FAIL, Constants.ERROR_MSG); + } + + public static Result error(T data, String msg) { + return restResult(data, FAIL, msg); + } + + public static Result error(int code, String msg) { + return restResult(null, code, msg); + } + + private static Result restResult(T data, int code, String msg) { + Result apiResult = new Result<>(); + apiResult.setCode(code); + apiResult.setData(data); + apiResult.setMsg(msg); + return apiResult; + } +} diff --git a/bwie-common/src/main/java/com/bwie/common/utils/JwtUtils.java b/bwie-common/src/main/java/com/bwie/common/utils/JwtUtils.java new file mode 100644 index 0000000..aac519f --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/utils/JwtUtils.java @@ -0,0 +1,108 @@ +package com.bwie.common.utils; + +import com.bwie.common.constants.JwtConstants; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; + +import java.util.Map; + +/** + * @description: Jwt工具类 + * @author DongZl + */ +public class JwtUtils { + + /** + * 秘钥 + */ + public static String secret = JwtConstants.SECRET; + + /** + * 从数据声明生成令牌 + * + * @param claims 数据声明 + * @return 令牌 + */ + public static String createToken(Map claims){ + return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact(); + } + + /** + * 从令牌中获取数据声明 + * + * @param token 令牌 + * @return 数据声明 + */ + public static Claims parseToken(String token){ + return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); + } + /** + * 根据令牌获取用户标识 + * + * @param token 令牌 + * @return 用户ID + */ + public static String getUserKey(String token){ + Claims claims = parseToken(token); + return getValue(claims, JwtConstants.USER_KEY); + } + /** + * 根据令牌获取用户标识 + * + * @param claims 身份信息 + * @return 用户ID + */ + public static String getUserKey(Claims claims){ + return getValue(claims, JwtConstants.USER_KEY); + } + /** + * 根据令牌获取用户ID + * + * @param token 令牌 + * @return 用户ID + */ + public static String getUserId(String token){ + Claims claims = parseToken(token); + return getValue(claims, JwtConstants.DETAILS_USER_ID); + } + /** + * 根据身份信息获取用户ID + * + * @param claims 身份信息 + * @return 用户ID + */ + public static String getUserId(Claims claims){ + return getValue(claims, JwtConstants.DETAILS_USER_ID); + } + /** + * 根据令牌获取用户名 + * + * @param token 令牌 + * @return 用户名 + */ + public static String getUserName(String token){ + Claims claims = parseToken(token); + return getValue(claims, JwtConstants.DETAILS_USERNAME); + } + /** + * 根据身份信息获取用户名 + * + * @param claims 身份信息 + * @return 用户名 + */ + public static String getUserName(Claims claims){ + return getValue(claims, JwtConstants.DETAILS_USERNAME); + } + /** + * 根据身份信息获取键值 + * + * @param claims 身份信息 + * @param key 键 + * @return 值 + */ + public static String getValue(Claims claims, String key){ + Object obj = claims.get(key); + return obj == null ? "" : obj.toString(); + } +} diff --git a/bwie-common/src/main/java/com/bwie/common/utils/StringUtils.java b/bwie-common/src/main/java/com/bwie/common/utils/StringUtils.java new file mode 100644 index 0000000..93c47fd --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/utils/StringUtils.java @@ -0,0 +1,68 @@ +package com.bwie.common.utils; + +import org.springframework.util.AntPathMatcher; + +import java.util.Collection; +import java.util.List; + +/** + * @author DongZl + * @description: 字符串处理工具类 + */ +public class StringUtils extends org.apache.commons.lang3.StringUtils { + + /** + * * 判断一个对象是否为空 + * + * @param object Object + * @return true:为空 false:非空 + */ + public static boolean isNull(Object object) { + return object == null; + } + + /** + * * 判断一个Collection是否为空, 包含List,Set,Queue + * + * @param coll 要判断的Collection + * @return true:为空 false:非空 + */ + public static boolean isEmpty(Collection coll) { + return isNull(coll) || coll.isEmpty(); + } + + /** + * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串 + * + * @param str 指定字符串 + * @param strs 需要检查的字符串数组 + * @return 是否匹配 + */ + public static boolean matches(String str, List strs) { + if (isEmpty(str) || isEmpty(strs)) { + return false; + } + for (String pattern : strs) { + if (isMatch(pattern, str)) + { + return true; + } + } + return false; + } + + /** + * 判断url是否与规则配置: + * ? 表示单个字符; + * * 表示一层路径内的任意字符串,不可跨层级; + * ** 表示任意层路径; + * + * @param pattern 匹配规则 + * @param url 需要匹配的url + * @return + */ + public static boolean isMatch(String pattern, String url) { + AntPathMatcher matcher = new AntPathMatcher(); + return matcher.match(pattern, url); + } +} diff --git a/bwie-common/src/main/java/com/bwie/common/utils/TelSmsUtils.java b/bwie-common/src/main/java/com/bwie/common/utils/TelSmsUtils.java new file mode 100644 index 0000000..b0a7322 --- /dev/null +++ b/bwie-common/src/main/java/com/bwie/common/utils/TelSmsUtils.java @@ -0,0 +1,89 @@ +package com.bwie.common.utils; + +import com.alibaba.fastjson.JSONObject; +import com.aliyun.dysmsapi20170525.Client; +import com.aliyun.dysmsapi20170525.models.SendSmsRequest; +import com.aliyun.dysmsapi20170525.models.SendSmsResponse; +import com.aliyun.teaopenapi.models.Config; +import lombok.extern.log4j.Log4j2; + +import java.util.Map; + +/** + * 短信工具类 + */ +@Log4j2 +public class TelSmsUtils { + + /** + * 阿里云主账号AccessKey,accessKeySecret拥有所有API的访问权限 + */ + private static String accessKeyId = "LTAI5tMRrNoxsBPgb6bYZWTW"; + private static String accessKeySecret = "r9LXZtt3ewEG2DHQ6DbAc65F0AFRA7"; + private static String templateCode = "SMS10001"; + /** + * 短信访问域名 + */ + private static String endpoint = "dysmsapi.aliyuncs.com"; + /** + * 短信签名 + */ + private static String signName = "登录验证"; + + /** + * 实例化短信对象 + */ + private static Client client; + + static { + log.info("初始化短信服务开始"); + long startTime = System.currentTimeMillis(); + try { + client = initClient(); + log.info("初始化短信成功:{}", signName); + } catch (Exception e) { + e.printStackTrace(); + } + log.info("初始化短信服务结束:耗时:{}MS", (System.currentTimeMillis() - startTime)); + } + + /** + * 初始化短信对象 + * + * @return + * @throws Exception + */ + private static Client initClient() throws Exception { + Config config = new Config() + // 您的AccessKey ID + .setAccessKeyId(accessKeyId) + // 您的AccessKey Secret + .setAccessKeySecret(accessKeySecret); + // 访问的域名 + config.endpoint = endpoint; + return new Client(config); + } + + /** + * 发送单条短信 + * + * @param tel + * @param sendDataMap + */ + public static String sendSms(String tel, Map sendDataMap) { + SendSmsRequest sendSmsRequest = new SendSmsRequest() + .setPhoneNumbers(tel) + .setSignName(signName) + .setTemplateCode(templateCode) + .setTemplateParam(JSONObject.toJSONString(sendDataMap)); + SendSmsResponse sendSmsResponse = null; + try { + log.info("发送短信验证码:消息内容是:【{}】", JSONObject.toJSONString(sendDataMap)); + sendSmsResponse = client.sendSms(sendSmsRequest); + } catch (Exception e) { + log.error("短信发送异常,手机号:【{}】,短信内容:【{}】,异常信息:【{}】", tel, sendDataMap, e); + } + return JSONObject.toJSONString(sendSmsResponse.getBody()); + } + +} diff --git a/bwie-common/src/main/resources/META-INF/spring.factories b/bwie-common/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000..29b2d0f --- /dev/null +++ b/bwie-common/src/main/resources/META-INF/spring.factories @@ -0,0 +1,4 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + com.bwie.common.config.RabbitmqConfig,\ + com.bwie.common.config.ConfirmCallbackConfig,\ + com.bwie.common.config.ReturnsCallbackConfig diff --git a/bwie-gateway/pom.xml b/bwie-gateway/pom.xml new file mode 100644 index 0000000..26c2e8a --- /dev/null +++ b/bwie-gateway/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + com.bwie + bwie-1016 + 1.0-SNAPSHOT + + + bwie-gateway + + + + + com.bwie + bwie-common + + + + + org.springframework.cloud + spring-cloud-starter-gateway + + + + com.alibaba.cloud + spring-cloud-alibaba-sentinel-gateway + + + + com.alibaba.csp + sentinel-spring-cloud-gateway-adapter + + + + + ${project.artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + diff --git a/bwie-gateway/src/main/java/com/bwie/gateway/GatewayApplication.java b/bwie-gateway/src/main/java/com/bwie/gateway/GatewayApplication.java new file mode 100644 index 0000000..53f63b1 --- /dev/null +++ b/bwie-gateway/src/main/java/com/bwie/gateway/GatewayApplication.java @@ -0,0 +1,19 @@ +package com.bwie.gateway; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/17 + */ +@SpringBootApplication +public class GatewayApplication { + + public static void main(String[] args) { + SpringApplication.run(GatewayApplication.class); + } + +} diff --git a/bwie-gateway/src/main/java/com/bwie/gateway/config/IgnoreWhitesConfig.java b/bwie-gateway/src/main/java/com/bwie/gateway/config/IgnoreWhitesConfig.java new file mode 100644 index 0000000..6676d17 --- /dev/null +++ b/bwie-gateway/src/main/java/com/bwie/gateway/config/IgnoreWhitesConfig.java @@ -0,0 +1,35 @@ +package com.bwie.gateway.config; + +import com.alibaba.fastjson.JSONObject; +import lombok.Data; +import lombok.extern.log4j.Log4j2; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +/** + * @ClassName: + * @Description: 加载配置白名单请求 + * @Author: zhuwenqiang + * @Date: 2023/10/19 + */ +@Configuration +@ConfigurationProperties(prefix = "ignore") +@Data +@Log4j2 +public class IgnoreWhitesConfig { + + private List whites = new ArrayList<>(); + + public void setWhites(List whites) { + log.info("加载系统白名单请求:{}", JSONObject.toJSON(whites)); + this.whites = whites; + } + + + + + +} diff --git a/bwie-gateway/src/main/java/com/bwie/gateway/filters/AuthFilter.java b/bwie-gateway/src/main/java/com/bwie/gateway/filters/AuthFilter.java new file mode 100644 index 0000000..f88a4a3 --- /dev/null +++ b/bwie-gateway/src/main/java/com/bwie/gateway/filters/AuthFilter.java @@ -0,0 +1,104 @@ +package com.bwie.gateway.filters; + +import cn.hutool.core.date.DateUnit; +import cn.hutool.core.date.DateUtil; +import com.alibaba.fastjson.JSONObject; +import com.bwie.common.constants.TokenConstants; +import com.bwie.common.domain.SysUser; +import com.bwie.common.utils.JwtUtils; +import com.bwie.common.utils.StringUtils; +import com.bwie.gateway.config.IgnoreWhitesConfig; +import com.bwie.gateway.utils.GatewayUtils; +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.*; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.util.Date; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * @ClassName: + * @Description: 鉴权过滤器 拦截请求验证 token + * @Author: zhuwenqiang + * @Date: 2023/10/19 + */ +@Component +public class AuthFilter implements GlobalFilter, Ordered { + + @Autowired + private IgnoreWhitesConfig ignoreWhitesConfig; + + @Autowired + private RedisTemplate redisTemplate; + + /** + * 过滤方法 只要在这个方法中实现业务 验证 token + *

+ * 会将不拦截的请求 配置到 配置文件中 + * + * @param exchange 请求的上下文 获取请求和响应对象 + * @param chain 网关过滤器链 放行 + * @return + */ + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + // 获取系统白名单请求 + List whites = ignoreWhitesConfig.getWhites(); + // 判断 当前 请求是否是 白名单的请求 + // 获取当前请求的 URI + ServerHttpRequest request = exchange.getRequest(); + String path = request.getURI().getPath(); + if (StringUtils.matches(path, whites)) { + // 白名单请求 放行 + return chain.filter(exchange); + } + // 验证 token 非空 + String token = request.getHeaders().getFirst(TokenConstants.TOKEN); + if (StringUtils.isBlank(token)) { + // 提示错误信息 + return GatewayUtils.errorResponse(exchange, "token不能为空!"); + } + // 合法性验证 + String userKey = null; + try { + userKey = JwtUtils.getUserKey(token); + } catch (Exception e) { + return GatewayUtils.errorResponse(exchange, "token不合法!"); + } + // token 有效性验证 + // 获取 userKey + if (!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey)) { + // 提示错误信息 + return GatewayUtils.errorResponse(exchange, "token过期!"); + } + // 续期 登录在10分钟以内自动续期 + // 获取用户的登录时间 + String userJSON = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey); + SysUser sysUser = JSONObject.parseObject(userJSON, SysUser.class); + Date loginDate = sysUser.getLoginDate(); + long min = DateUtil.between(loginDate, new Date(), DateUnit.MINUTE); + if (min <= 10) { + redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY + userKey, 30, TimeUnit.MINUTES); + } + // 放行 + return chain.filter(exchange); + } + + /** + * 过滤器的执行顺序 【过滤器可以有多个】 返回的值越小 优先级越高 + * + * @return + */ + @Override + public int getOrder() { + return 0; + } +} diff --git a/bwie-gateway/src/main/java/com/bwie/gateway/filters/LogFilter.java b/bwie-gateway/src/main/java/com/bwie/gateway/filters/LogFilter.java new file mode 100644 index 0000000..3d14542 --- /dev/null +++ b/bwie-gateway/src/main/java/com/bwie/gateway/filters/LogFilter.java @@ -0,0 +1,29 @@ +package com.bwie.gateway.filters; + +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.core.*; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/19 + */ +//@Component +public class LogFilter implements GlobalFilter, Ordered { + + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + return null; + } + + @Override + public int getOrder() { + return 1; + } +} diff --git a/bwie-gateway/src/main/java/com/bwie/gateway/utils/GatewayUtils.java b/bwie-gateway/src/main/java/com/bwie/gateway/utils/GatewayUtils.java new file mode 100644 index 0000000..0eeaed9 --- /dev/null +++ b/bwie-gateway/src/main/java/com/bwie/gateway/utils/GatewayUtils.java @@ -0,0 +1,102 @@ +package com.bwie.gateway.utils; + +import com.alibaba.fastjson.JSONObject; +import com.bwie.common.result.Result; +import com.bwie.common.utils.StringUtils; +import lombok.extern.log4j.Log4j2; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +/** + * @author DongZl + * @description: 网关处理工具类 + */ +@Log4j2 +public class GatewayUtils { + /** + * 添加请求头参数 + * + * @param mutate 修改对象 + * @param key 键 + * @param value 值 + */ + public static void addHeader(ServerHttpRequest.Builder mutate, String key, Object value) { + if (StringUtils.isEmpty(key)) { + log.warn("添加请求头参数键不可以为空"); + return; + } + if (value == null) { + log.warn("添加请求头参数:[{}]值为空", key); + return; + } + String valueStr = value.toString(); + mutate.header(key, valueStr); + log.info("添加请求头参数成功 - 键:[{}] , 值:[{}]", key, value); + } + + /** + * 删除请求头参数 + * + * @param mutate 修改对象 + * @param key 键 + */ + public static void removeHeader(ServerHttpRequest.Builder mutate, String key) { + if (StringUtils.isEmpty(key)) { + log.warn("删除请求头参数键不可以为空"); + return; + } + mutate.headers(httpHeaders -> httpHeaders.remove(key)).build(); + log.info("删除请求头参数 - 键:[{}]", key); + } + + /** + * 错误结果响应 + * + * @param exchange 响应上下文 + * @param msg 响应消息 + * @return + */ + public static Mono errorResponse(ServerWebExchange exchange, String msg, HttpStatus httpStatus) { + ServerHttpResponse response = exchange.getResponse(); + //设置HTTP响应头状态 + response.setStatusCode(httpStatus); + //设置HTTP响应头文本格式 + response.getHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json"); + //定义响应内容 + Result result = Result.error(msg); + String resultJson = JSONObject.toJSONString(result); + log.error("[鉴权异常处理]请求路径:[{}],异常信息:[{}],响应结果:[{}]", exchange.getRequest().getPath(), msg, resultJson); + DataBuffer dataBuffer = response.bufferFactory().wrap(resultJson.getBytes()); + //进行响应 + return response.writeWith(Mono.just(dataBuffer)); + } + + /** + * 错误结果响应 + * + * @param exchange 响应上下文 + * @param msg 响应消息 + * @return + */ + public static Mono errorResponse(ServerWebExchange exchange, String msg) { + ServerHttpResponse response = exchange.getResponse(); + //设置HTTP响应头状态 + response.setStatusCode(HttpStatus.OK); + //设置HTTP响应头文本格式 + response.getHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json"); + //定义响应内容 + Result result = Result.error(msg); + String resultJson = JSONObject.toJSONString(result); + log.error("[鉴权异常处理]请求路径:[{}],异常信息:[{}],响应结果:[{}]", exchange.getRequest().getPath(), msg, resultJson); + DataBuffer dataBuffer = response.bufferFactory().wrap(resultJson.getBytes()); + //进行响应 + return response.writeWith(Mono.just(dataBuffer)); + } + + +} diff --git a/bwie-gateway/src/main/resources/bootstrap.yml b/bwie-gateway/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..0b35b62 --- /dev/null +++ b/bwie-gateway/src/main/resources/bootstrap.yml @@ -0,0 +1,30 @@ +# Tomcat +server: + port: 18080 +# Spring +spring: + application: + # 应用名称 + name: bwie-gateway + profiles: + # 环境配置 + active: dev + main: + # 允许使用循环引用 + allow-circular-references: true + # 允许定义相同的bean对象 去覆盖原有的 + allow-bean-definition-overriding: true + cloud: + nacos: + discovery: + # 服务注册地址 + server-addr: 123.249.113.136:8848 + config: + # 配置中心地址 + server-addr: 123.249.113.136:8848 + # 配置文件格式 + file-extension: yml + namespace: a9b66e92-e507-47ba-9674-6f939f793aca + # 共享配置 + shared-configs: + - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} diff --git a/bwie-modules/bwie-es/pom.xml b/bwie-modules/bwie-es/pom.xml new file mode 100644 index 0000000..e6fd893 --- /dev/null +++ b/bwie-modules/bwie-es/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + com.bwie + bwie-modules + 1.0-SNAPSHOT + + + bwie-es + + + + com.bwie + bwie-common + + + org.springframework.boot + spring-boot-starter-web + + + + org.elasticsearch.client + elasticsearch-rest-high-level-client + + + + diff --git a/bwie-modules/bwie-es/src/main/java/com/bwie/es/ESApplication.java b/bwie-modules/bwie-es/src/main/java/com/bwie/es/ESApplication.java new file mode 100644 index 0000000..739f823 --- /dev/null +++ b/bwie-modules/bwie-es/src/main/java/com/bwie/es/ESApplication.java @@ -0,0 +1,23 @@ +package com.bwie.es; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/27 + */ +@SpringBootApplication +@EnableFeignClients +@EnableScheduling +public class ESApplication { + + public static void main(String[] args) { + SpringApplication.run(ESApplication.class); + } + +} diff --git a/bwie-modules/bwie-es/src/main/java/com/bwie/es/config/InitRestHighLevelClient.java b/bwie-modules/bwie-es/src/main/java/com/bwie/es/config/InitRestHighLevelClient.java new file mode 100644 index 0000000..f78aa85 --- /dev/null +++ b/bwie-modules/bwie-es/src/main/java/com/bwie/es/config/InitRestHighLevelClient.java @@ -0,0 +1,35 @@ +package com.bwie.es.config; + +import lombok.Data; +import org.apache.http.HttpHost; +import org.elasticsearch.client.RestClient; +import org.elasticsearch.client.RestHighLevelClient; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @ClassName: + * @Description: 初始化 RestHighLevelClient + * @Author: zhuwenqiang + * @Date: 2023/10/27 + */ +@Configuration +@ConfigurationProperties(prefix = "es") +@Data +public class InitRestHighLevelClient { + + private String host; + + private int port; + + private String scheme; + + @Bean + public RestHighLevelClient init() { + return new RestHighLevelClient( + RestClient.builder(new HttpHost(host, port, scheme)) + ); + } + +} diff --git a/bwie-modules/bwie-es/src/main/java/com/bwie/es/consumer/AddGoodsConsumer.java b/bwie-modules/bwie-es/src/main/java/com/bwie/es/consumer/AddGoodsConsumer.java new file mode 100644 index 0000000..81ffe65 --- /dev/null +++ b/bwie-modules/bwie-es/src/main/java/com/bwie/es/consumer/AddGoodsConsumer.java @@ -0,0 +1,68 @@ +package com.bwie.es.consumer; + +import com.alibaba.fastjson.JSONObject; +import com.bwie.common.constants.MQQueueNameConstants; +import com.bwie.common.domain.vo.GoodsVO; +import com.bwie.es.service.GoodsService; +import com.rabbitmq.client.Channel; +import lombok.extern.log4j.Log4j2; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +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.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/30 + */ +@Component +@Log4j2 +public class AddGoodsConsumer { + + @Autowired + private RedisTemplate redisTemplate; + + @Autowired + private GoodsService goodsService; + + @RabbitListener(queuesToDeclare = {@Queue(MQQueueNameConstants.ADD_GOODS_ES_QUEUE_NAME)}) + public void addGoodsConsumer(Message message, GoodsVO goodsVO, Channel channel) { + log.info("消息队列:{},接收到消息,消息的内容是:{},开始消费...", + MQQueueNameConstants.ADD_GOODS_ES_QUEUE_NAME, JSONObject.toJSONString(goodsVO)); + // 获取 messageId + String messageId = message.getMessageProperties().getMessageId(); + try { + long count = redisTemplate.opsForSet().add(MQQueueNameConstants.ADD_GOODS_ES_QUEUE_NAME, messageId); + if (count == 1) { + // 正常消费 + List list = Arrays.asList(goodsVO); + goodsService.batchAdd(list); + // 确认 + channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); + log.info("消息队列:{},接收到消息,消息的内容是:{},消费成功...", + MQQueueNameConstants.ADD_GOODS_ES_QUEUE_NAME, JSONObject.toJSONString(goodsVO)); + } + } catch (Exception e) { + log.error("消息队列:{},接收到消息,消息的内容是:{},消费消息异常,异常信息:{}", + MQQueueNameConstants.ADD_GOODS_ES_QUEUE_NAME, JSONObject.toJSONString(goodsVO), e); + redisTemplate.opsForSet().remove(MQQueueNameConstants.ADD_GOODS_ES_QUEUE_NAME, messageId); + try { + channel.basicReject(message.getMessageProperties().getDeliveryTag(), true); + } catch (IOException ex) { + log.error("消息队列:{},接收到消息,消息的内容是:{},消息回退异常,异常信息:{}", + MQQueueNameConstants.ADD_GOODS_ES_QUEUE_NAME, JSONObject.toJSONString(goodsVO), ex); + } + } + } + +} diff --git a/bwie-modules/bwie-es/src/main/java/com/bwie/es/cotroller/ArticleController.java b/bwie-modules/bwie-es/src/main/java/com/bwie/es/cotroller/ArticleController.java new file mode 100644 index 0000000..a3dd56b --- /dev/null +++ b/bwie-modules/bwie-es/src/main/java/com/bwie/es/cotroller/ArticleController.java @@ -0,0 +1,157 @@ +package com.bwie.es.cotroller; + +import com.alibaba.fastjson.JSONObject; +import com.bwie.common.domain.Article; +import com.bwie.common.domain.dto.ArticleSearchDTO; +import com.bwie.common.domain.vo.CountPriceAggVO; +import com.bwie.common.result.PageResult; +import com.bwie.common.result.Result; +import com.bwie.es.service.ArticleService; +import com.bwie.es.service.GoodsService; +import lombok.extern.log4j.Log4j2; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/27 + */ +@RestController +@RequestMapping("es/article") +@Log4j2 +public class ArticleController { + + @Autowired + private HttpServletRequest request; + + @Autowired + private ArticleService articleService; + + /** + * 添加 + */ + @PostMapping + public Result add(@RequestBody Article article) { + log.info("功能名称:添加文章到ES,请求URI:{},请求方式:{},请求参数:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(article)); + articleService.add(article); + Result result = Result.success(); + log.info("功能名称:添加文章到ES,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + /** + * 批操作 + */ + @PostMapping("batchAdd") + public Result batchAdd(@RequestBody List
articles) { + log.info("功能名称:批量添加文章到ES,请求URI:{},请求方式:{},请求参数:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(articles)); + articleService.batchAdd(articles); + Result result = Result.success(); + log.info("功能名称:批量添加文章到ES,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + /** + * 修改 + */ + @PutMapping + public Result update(@RequestBody Article article) { + log.info("功能名称:修改文章到ES,请求URI:{},请求方式:{},请求参数:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(article)); + articleService.update(article); + Result result = Result.success(); + log.info("功能名称:修改文章到ES,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + /** + * 删除 + */ + @DeleteMapping("delete/{id}") + public Result delete(@PathVariable String id) { + log.info("功能名称:删除文章,请求URI:{},请求方式:{},请求参数:{}", request.getRequestURI(), + request.getMethod(), id); + articleService.delete(id); + Result result = Result.success(); + log.info("功能名称:删除文章,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + /** + * 主键查询 + */ + @GetMapping("findById/{id}") + public Result
findById(@PathVariable String id) { + log.info("功能名称:主键查询文章,请求URI:{},请求方式:{},请求参数:{}", request.getRequestURI(), + request.getMethod(), id); + Article article = articleService.findById(id); + Result
result = Result.success(article); + log.info("功能名称:主键查询文章,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + /** + * 搜索 + */ + @PostMapping("search") + public Result> search(@RequestBody ArticleSearchDTO articleSearchDTO) { + log.info("功能名称:文章搜索,请求URI:{},请求方式:{},请求参数:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(articleSearchDTO)); + Result> result = articleService.search(articleSearchDTO); + log.info("功能名称:文章搜索,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + @Autowired + private GoodsService goodsService; + + /** + * 聚合 + */ + @GetMapping("maxPrice") + public Result maxPrice() { + log.info("功能名称:查询商品最大价格,请求URI:{},请求方式:{}", request.getRequestURI(), + request.getMethod()); + Double maxPrice = goodsService.maxPrice(); + Result result = Result.success(maxPrice); + log.info("功能名称:查询商品最大价格,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + + /** + * DTO 数据传输对象 用来接收参数 以及 各层之间传递 + * VO 视图对象 用于将数据传递给 模板渲染引擎层传输 + * BO Business Object + * + * @return + */ + + @GetMapping("countPrice") + public Result> countPrice() { + log.info("功能名称:查询每种价格商品的数量,请求URI:{},请求方式:{}", request.getRequestURI(), + request.getMethod()); + List countPrices = goodsService.countPrice(); + Result> result = Result.success(countPrices); + log.info("功能名称:查询每种价格商品的数量,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + + +} diff --git a/bwie-modules/bwie-es/src/main/java/com/bwie/es/remote/GoodsFeignService.java b/bwie-modules/bwie-es/src/main/java/com/bwie/es/remote/GoodsFeignService.java new file mode 100644 index 0000000..5f5039d --- /dev/null +++ b/bwie-modules/bwie-es/src/main/java/com/bwie/es/remote/GoodsFeignService.java @@ -0,0 +1,26 @@ +package com.bwie.es.remote; + +import com.bwie.common.domain.vo.GoodsVO; +import com.bwie.common.result.Result; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; + +import java.util.List; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/30 + */ +@FeignClient("bwie-goods") +public interface GoodsFeignService { + + /** + * 查询所有的商品的信息 + * @return + */ + @GetMapping("findAll") + public Result> findAll(); + +} diff --git a/bwie-modules/bwie-es/src/main/java/com/bwie/es/service/ArticleService.java b/bwie-modules/bwie-es/src/main/java/com/bwie/es/service/ArticleService.java new file mode 100644 index 0000000..67f608c --- /dev/null +++ b/bwie-modules/bwie-es/src/main/java/com/bwie/es/service/ArticleService.java @@ -0,0 +1,54 @@ +package com.bwie.es.service; + +import com.bwie.common.domain.Article; +import com.bwie.common.domain.dto.ArticleSearchDTO; +import com.bwie.common.result.PageResult; +import com.bwie.common.result.Result; + +import java.util.List; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/28 + */ +public interface ArticleService { + /** + * 添加文章到ES + * @param article + */ + void add(Article article); + + /** + * 批量添加文章到ES + * @param articles + */ + void batchAdd(List
articles); + + /** + * 修改文章到ES + * @param article + */ + void update(Article article); + + /** + * 删除文章 + * @param id + */ + void delete(String id); + + /** + * 主键查询文章 + * @param id + * @return + */ + Article findById(String id); + + /** + * 文章搜索 + * @param articleSearchDTO + * @return + */ + Result> search(ArticleSearchDTO articleSearchDTO); +} diff --git a/bwie-modules/bwie-es/src/main/java/com/bwie/es/service/GoodsService.java b/bwie-modules/bwie-es/src/main/java/com/bwie/es/service/GoodsService.java new file mode 100644 index 0000000..48e4a8c --- /dev/null +++ b/bwie-modules/bwie-es/src/main/java/com/bwie/es/service/GoodsService.java @@ -0,0 +1,23 @@ +package com.bwie.es.service; + +import com.bwie.common.domain.vo.CountPriceAggVO; +import com.bwie.common.domain.vo.GoodsVO; + +import java.util.List; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/30 + */ +public interface GoodsService { + + void batchAdd(List goods); + + Double maxPrice(); + + List countPrice(); + + +} diff --git a/bwie-modules/bwie-es/src/main/java/com/bwie/es/service/impl/ArticleServiceImpl.java b/bwie-modules/bwie-es/src/main/java/com/bwie/es/service/impl/ArticleServiceImpl.java new file mode 100644 index 0000000..da290dc --- /dev/null +++ b/bwie-modules/bwie-es/src/main/java/com/bwie/es/service/impl/ArticleServiceImpl.java @@ -0,0 +1,274 @@ +package com.bwie.es.service.impl; + +import com.alibaba.fastjson.JSONObject; +import com.bwie.common.constants.TokenConstants; +import com.bwie.common.domain.Article; +import com.bwie.common.domain.SysUser; +import com.bwie.common.domain.dto.ArticleSearchDTO; +import com.bwie.common.result.PageResult; +import com.bwie.common.result.Result; +import com.bwie.common.utils.JwtUtils; +import com.bwie.common.utils.StringUtils; +import com.bwie.es.service.ArticleService; +import lombok.extern.log4j.Log4j2; +import org.bouncycastle.cert.ocsp.Req; +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.action.bulk.BulkRequest; +import org.elasticsearch.action.delete.DeleteRequest; +import org.elasticsearch.action.get.GetRequest; +import org.elasticsearch.action.get.GetResponse; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.index.IndexResponse; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.action.update.UpdateRequest; +import org.elasticsearch.client.RequestOptions; +import org.elasticsearch.client.RestHighLevelClient; +import org.elasticsearch.common.text.Text; +import org.elasticsearch.common.xcontent.XContentType; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.search.SearchHit; +import org.elasticsearch.search.SearchHits; +import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; +import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; +import org.elasticsearch.search.sort.SortOrder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +import javax.naming.directory.SearchResult; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.*; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/28 + */ +@Service +@Log4j2 +public class ArticleServiceImpl implements ArticleService { + + /** + * 索引名称 + */ + private static final String INDEX_NAME = "article"; + + @Autowired + private RestHighLevelClient restHighLevelClient; + + @Autowired + private HttpServletRequest request; + + @Autowired + private RedisTemplate redisTemplate; + + @Override + public void add(Article article) { + try { + // 创建 IndexRequest对象 + IndexRequest indexRequest = new IndexRequest(INDEX_NAME); + // 设置文档 id 可选 + indexRequest.id(UUID.randomUUID().toString()); + // 设置添加时间 + article.setCreateTime(new Date()); + // 设置添加的数据【JSON格式】 + indexRequest.source(JSONObject.toJSONString(article), XContentType.JSON); + // 同步执行 + restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); + // 异步执行 +// restHighLevelClient.indexAsync(indexRequest, RequestOptions.DEFAULT, new ActionListener() { +// /** +// * 执行成功 +// * @param indexResponse +// */ +// @Override +// public void onResponse(IndexResponse indexResponse) { +// +// } +// +// /** +// * 执行失败 +// * @param e +// */ +// @Override +// public void onFailure(Exception e) { +// +// } +// }); + } catch (IOException e) { + log.error("添加文章异常,请求参数:{},异常信息:{}", JSONObject.toJSONString(article), e.getMessage()); + } + } + + @Override + public void batchAdd(List
articles) { + try { + // 创建 BulkRequest 对象 + BulkRequest bulkRequest = new BulkRequest(); + // 遍历 articles 创建 IndexRequest对象 + articles.forEach(article -> { + // 设置创建时间 + article.setCreateTime(new Date()); + bulkRequest.add( + new IndexRequest(INDEX_NAME) + .id(UUID.randomUUID().toString()) + .source(JSONObject.toJSONString(article), XContentType.JSON)); + }); + // 执行发送请求 + restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); + } catch (Exception e) { + log.error("批量添加文章异常,请求参数:{},异常信息:{}", JSONObject.toJSONString(articles), e.getMessage()); + } + } + + @Override + public void update(Article article) { + try { + // 创建 UpdateRequest 对象 + UpdateRequest updateRequest = new UpdateRequest(INDEX_NAME, article.getId()); + // 设置修改的数据 + updateRequest.doc(JSONObject.toJSONString(article), XContentType.JSON); + // 执行修改请求 + restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT); + } catch (Exception e) { + log.error("修改文章异常,请求参数:{},异常信息:{}", JSONObject.toJSONString(article), e.getMessage()); + } + } + + @Override + public void delete(String id) { + try { + // 创建 DeleteRequest + DeleteRequest deleteRequest = new DeleteRequest(INDEX_NAME, id); + // 执行删除请求 + restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT); + } catch (Exception e) { + log.error("删除文章,请求参数:{},异常信息:{}", id, e.getMessage()); + } + } + + @Override + public Article findById(String id) { + try { + // 创建 GetRequest 对象 + GetRequest getRequest = new GetRequest(INDEX_NAME, id); + // 执行查询操作 + GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT); + // 处理响应结果 + if (getResponse.isExists()) { + // 获取查询到的结果 + String sourceAsString = getResponse.getSourceAsString(); + // 反序列化 + Article article = JSONObject.parseObject(sourceAsString, Article.class); + // 设置 id + article.setId(getResponse.getId()); + return article; + } + } catch (Exception e) { + log.error("主键查询文章异常,请求参数:{},异常信息:{}", id, e.getMessage()); + } + return null; + } + + @Override + public Result> search(ArticleSearchDTO articleSearchDTO) { + // 定义 总记录数 + long total = 0; + // 当前页数据 + List
articles = new ArrayList<>(); + try { + // 创建SearchRequest 对象 + SearchRequest searchRequest = new SearchRequest(INDEX_NAME); + // 构建 搜索条件 对象 所有的搜索条件 都需要给它 + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + // 构建条件拼接对象 + BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); + // 拼接查询条件 + if (!StringUtils.isBlank(articleSearchDTO.getTitle())) { + boolQueryBuilder.must(QueryBuilders.matchQuery("title", articleSearchDTO.getTitle())); + } + if (!StringUtils.isEmpty(articleSearchDTO.getAuthor())) { + boolQueryBuilder.must(QueryBuilders.matchQuery("author", articleSearchDTO.getAuthor())); + } + // 区间 + if (articleSearchDTO.getBeginDate() != null) { + boolQueryBuilder.must(QueryBuilders.rangeQuery("createTime").gte(articleSearchDTO.getBeginDate().getTime())); + } + if (articleSearchDTO.getEndDate() != null) { + boolQueryBuilder.must(QueryBuilders.rangeQuery("createTime").lte(articleSearchDTO.getEndDate().getTime())); + } + // 判断当前登录用户的角色 + Integer role = userInfo().getRole(); + if (role == 2) { + boolQueryBuilder.must(QueryBuilders.matchQuery("createBy", userInfo().getId())); + } + // 将查询条件 给 searchSourceBuilder + searchSourceBuilder.query(boolQueryBuilder); + // 分页 + searchSourceBuilder.from((articleSearchDTO.getPageNum() - 1) * articleSearchDTO.getPageSize()); + searchSourceBuilder.size(articleSearchDTO.getPageSize()); + // 排序 + searchSourceBuilder.sort("createTime", SortOrder.DESC); + // 高亮 ?? preTags 前面标签 postTags 后面标签 ddd 华为手机遥遥领先 + searchSourceBuilder.highlighter( + new HighlightBuilder().field("title").preTags("").postTags("")); + // 将 查询条件对象 给 searchRequest + searchRequest.source(searchSourceBuilder); + // 执行查询操作 + SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); + // 获取查询的命中 + SearchHits searchHits = searchResponse.getHits(); + // 获取总记录数 + total = searchHits.getTotalHits().value; + // 获取当前页数据 + SearchHit[] hits = searchHits.getHits(); + // 遍历数组 + for (SearchHit hit : hits) { + // 获取 source + String sourceAsString = hit.getSourceAsString(); + // 反序列化 + Article article = JSONObject.parseObject(sourceAsString, Article.class); + // 替换高亮字段 + // 获取高亮 map 集合 + Map highlightFields = hit.getHighlightFields(); + if (highlightFields != null && highlightFields.size() > 0) { + HighlightField highlightField = highlightFields.get("title"); + if (highlightField != null) { + // 获取 高亮 碎片 + Text[] fragments = highlightField.getFragments(); + // 拼接 华为手机遥遥领先 -> 华为手机遥遥领先 + StringBuilder sb = new StringBuilder(); + for (Text fragment : fragments) { + sb.append(fragment); + } + // 替换 + article.setTitle(sb.toString()); + } + } + // 设置 id + article.setId(hit.getId()); + // 添加到结果集 + articles.add(article); + } + } catch (Exception e) { + log.error("文章搜索异常,请求参数:{},异常信息:{}", JSONObject.toJSONString(articleSearchDTO), e.getMessage()); + } + // 返回结果 + return PageResult.toResult(total, articles); + } + + + private SysUser userInfo() { + String token = request.getHeader(TokenConstants.TOKEN); + String userKey = JwtUtils.getUserKey(token); + String useJson = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey); + return JSONObject.parseObject(useJson, SysUser.class); + } + +} diff --git a/bwie-modules/bwie-es/src/main/java/com/bwie/es/service/impl/GoodsServiceImpl.java b/bwie-modules/bwie-es/src/main/java/com/bwie/es/service/impl/GoodsServiceImpl.java new file mode 100644 index 0000000..f7d1331 --- /dev/null +++ b/bwie-modules/bwie-es/src/main/java/com/bwie/es/service/impl/GoodsServiceImpl.java @@ -0,0 +1,137 @@ +package com.bwie.es.service.impl; + +import com.alibaba.fastjson.JSONObject; +import com.bwie.common.domain.vo.CountPriceAggVO; +import com.bwie.common.domain.vo.GoodsVO; +import com.bwie.es.service.GoodsService; +import org.bouncycastle.cert.ocsp.Req; +import org.elasticsearch.action.bulk.BulkRequest; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.client.RequestOptions; +import org.elasticsearch.client.RestHighLevelClient; +import org.elasticsearch.common.xcontent.XContentType; +import org.elasticsearch.search.aggregations.Aggregation; +import org.elasticsearch.search.aggregations.AggregationBuilders; +import org.elasticsearch.search.aggregations.Aggregations; +import org.elasticsearch.search.aggregations.bucket.terms.Terms; +import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; +import org.elasticsearch.search.aggregations.metrics.Avg; +import org.elasticsearch.search.aggregations.metrics.Max; +import org.elasticsearch.search.aggregations.metrics.MaxAggregationBuilder; +import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/30 + */ +@Service +public class GoodsServiceImpl implements GoodsService { + + /** + * 索引名称 + */ + private static final String INDEX_NAME = "goods"; + + @Autowired + private RestHighLevelClient restHighLevelClient; + + @Override + public void batchAdd(List goods) { + try { + // 分批次同步 每次取出 100 + // 每次取出100条数据 + int batchSize = 100; + for (int i = 0; i < goods.size(); i += batchSize) { + BulkRequest bulkRequest = new BulkRequest(); + List batch = goods.subList(i, Math.min(goods.size(), i + batchSize)); + batch.forEach(good -> { + bulkRequest.add( + new IndexRequest(INDEX_NAME) + .id(good.getId() + "") + .source(JSONObject.toJSONString(good), XContentType.JSON)); + }); + restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); + } + } catch (Exception e) { + + } + } + + @Override + public Double maxPrice() { + Double maxPrice = 0.00; + try { + // 创建 搜索请求对象 + SearchRequest searchRequest = new SearchRequest("goods"); + // 构建 SearchSourceBuilder + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + // 构建 集合查询对象 max("聚合函数的名称") 名称随意 field("列名") 对那一列进行聚合 + // 将聚合查询的条件 给 SearchSourceBuilder + searchSourceBuilder.aggregation(AggregationBuilders.avg("avg_price").field("price")); + // 将 searchSourceBuilder 给 searchRequest + searchRequest.source(searchSourceBuilder); + // 小执行查询 + SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); + // 处理结果集 + Avg avg = searchResponse.getAggregations().get("avg_price"); + maxPrice = avg.getValue(); + } catch (Exception e) { + + } + return maxPrice; + } + + @Override + public List countPrice() { + List priceAggVOList = new ArrayList<>(); + try { + SearchRequest searchRequest = new SearchRequest("goods"); + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("count_price").field("price"); + searchSourceBuilder.aggregation(aggregationBuilder); + searchRequest.source(searchSourceBuilder); + + SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); + Terms terms = searchResponse.getAggregations().get("count_price"); + List buckets = terms.getBuckets(); + CountPriceAggVO countPriceAggVO = null; + for (Terms.Bucket bucket : buckets) { + String key = bucket.getKeyAsString(); + long docCount = bucket.getDocCount(); + countPriceAggVO = new CountPriceAggVO(); + countPriceAggVO.setKeyName(key); + countPriceAggVO.setCount(docCount); + priceAggVOList.add(countPriceAggVO); + } + } catch (Exception e) { + + } + return priceAggVOList; + } + + public static void main(String[] args) { + // 假设你有一个List集合 + List dataList = new ArrayList<>(); + for (int i = 0; i < 500; i++) { + dataList.add("Data " + i); + } + + // 每次取出100条数据 + int batchSize = 100; + for (int i = 0; i < dataList.size(); i += batchSize) { + List batch = dataList.subList(i, Math.min(dataList.size(), i + batchSize)); + // 在这里处理batch,例如打印出来 + System.out.println(batch); + } + } + +} diff --git a/bwie-modules/bwie-es/src/main/java/com/bwie/es/sync/SyncGoods.java b/bwie-modules/bwie-es/src/main/java/com/bwie/es/sync/SyncGoods.java new file mode 100644 index 0000000..0bb8e9f --- /dev/null +++ b/bwie-modules/bwie-es/src/main/java/com/bwie/es/sync/SyncGoods.java @@ -0,0 +1,48 @@ +package com.bwie.es.sync; + +import com.bwie.common.domain.vo.GoodsVO; +import com.bwie.common.result.Result; +import com.bwie.es.remote.GoodsFeignService; +import com.bwie.es.service.GoodsService; +import lombok.extern.log4j.Log4j2; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import java.util.List; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/30 + */ +@Component +@Log4j2 +public class SyncGoods { + + @Autowired + private GoodsFeignService goodsFeignService; + + @Autowired + private GoodsService goodsService; + + /** + * 同步商品数据到 es + */ +// @Scheduled(cron = "0 0/1 * * * ?") + public void syncGoods() { + // 查询 商品的数据 + Result> all = goodsFeignService.findAll(); + List data = all.getData(); + // 同步 + if (!CollectionUtils.isEmpty(data)) { + log.info("同步商品信息,查询到{}条商品信息,开始同步...", data.size()); + long s = System.currentTimeMillis(); + goodsService.batchAdd(data); + log.info("同步商品信息结束,用时{}毫秒...", (System.currentTimeMillis() - s)); + } + } + +} diff --git a/bwie-modules/bwie-es/src/main/java/com/bwie/es/sync/SyncGoods2.java b/bwie-modules/bwie-es/src/main/java/com/bwie/es/sync/SyncGoods2.java new file mode 100644 index 0000000..9e34d4e --- /dev/null +++ b/bwie-modules/bwie-es/src/main/java/com/bwie/es/sync/SyncGoods2.java @@ -0,0 +1,50 @@ +package com.bwie.es.sync; + +import com.bwie.common.domain.vo.GoodsVO; +import com.bwie.common.result.Result; +import com.bwie.es.remote.GoodsFeignService; +import com.bwie.es.service.GoodsService; +import lombok.extern.log4j.Log4j2; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import java.util.List; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/30 + */ +//@Component +@Log4j2 +public class SyncGoods2 implements ApplicationRunner { + @Override + public void run(ApplicationArguments args) throws Exception { + + } + +// @Autowired +// private GoodsFeignService goodsFeignService; +// +// @Autowired +// private GoodsService goodsService; +// +// @Override +// public void run(ApplicationArguments args) throws Exception { +// // 查询 商品的数据 +// Result> all = goodsFeignService.findAll(); +// List data = all.getData(); +// // 同步 +// if (!CollectionUtils.isEmpty(data)) { +// log.info("同步商品信息,查询到{}条商品信息,开始同步...", data.size()); +// long s = System.currentTimeMillis(); +// goodsService.batchAdd(data); +// log.info("同步商品信息结束,用时{}毫秒...", (System.currentTimeMillis() - s)); +// } +// } + +} diff --git a/bwie-modules/bwie-es/src/main/resources/bootstrap.yml b/bwie-modules/bwie-es/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..8fe827e --- /dev/null +++ b/bwie-modules/bwie-es/src/main/resources/bootstrap.yml @@ -0,0 +1,34 @@ +# Tomcat +server: + port: 9007 +# Spring +spring: + main: + allow-circular-references: true # 允许循环依赖 + jackson: # json 序列化 和 返序列化 转换 + date-format: yyyy-MM-dd HH:mm:ss + time-zone: GMT+8 + application: + # 应用名称 + name: bwie-es + profiles: + # 环境配置 + active: dev + cloud: + nacos: + discovery: + # 服务注册地址 + server-addr: 123.249.113.136:8848 + config: + # 配置中心地址 + server-addr: 123.249.113.136:8848 + namespace: a9b66e92-e507-47ba-9674-6f939f793aca + # 配置文件格式 + file-extension: yml + # 共享配置 + shared-configs: + - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} +es: + host: 123.249.113.136 + port: 9200 + scheme: http diff --git a/bwie-modules/bwie-goods/pom.xml b/bwie-modules/bwie-goods/pom.xml new file mode 100644 index 0000000..27cc391 --- /dev/null +++ b/bwie-modules/bwie-goods/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.bwie + bwie-modules + 1.0-SNAPSHOT + + + bwie-goods + + + + + com.bwie + bwie-common + + + + org.springframework.boot + spring-boot-starter-web + + + + com.alibaba + druid-spring-boot-starter + 1.2.8 + + + + mysql + mysql-connector-java + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 2.2.2 + + + + com.github.pagehelper + pagehelper-spring-boot-starter + 1.4.1 + + + + diff --git a/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/GoodsApplication.java b/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/GoodsApplication.java new file mode 100644 index 0000000..1a033cf --- /dev/null +++ b/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/GoodsApplication.java @@ -0,0 +1,19 @@ +package com.bwie.goods; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/18 + */ +@SpringBootApplication +public class GoodsApplication { + + public static void main(String[] args) { + SpringApplication.run(GoodsApplication.class); + } + +} diff --git a/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/controller/GoodsController.java b/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/controller/GoodsController.java new file mode 100644 index 0000000..3dbe993 --- /dev/null +++ b/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/controller/GoodsController.java @@ -0,0 +1,64 @@ +package com.bwie.goods.controller; + +import com.alibaba.fastjson.JSONObject; +import com.bwie.common.domain.Goods; +import com.bwie.common.domain.dto.GoodsQueryDTO; +import com.bwie.common.domain.vo.GoodsVO; +import com.bwie.common.result.PageResult; +import com.bwie.common.result.Result; +import com.bwie.goods.service.GoodsService; +import lombok.extern.log4j.Log4j2; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/18 + */ +@RestController +@Log4j2 +public class GoodsController { + + @Autowired + private HttpServletRequest request; + + @Autowired + private GoodsService goodsService; + + /** + * 查询商品列表 + * @param goodsQueryDTO fastjson alibaba goggle Gson Jackson + * @return + */ + @PostMapping("list") + public Result> list(@RequestBody GoodsQueryDTO goodsQueryDTO) { + log.info("功能名称:查询商品列表,请求URI:{},请求方式:{},请求参数:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(goodsQueryDTO)); + Result> result = goodsService.list(goodsQueryDTO); + log.info("功能名称:查询商品列表,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + /** + * 查询所有的商品的信息 + * @return + */ + @GetMapping("findAll") + public Result> findAll() { + return Result.success(goodsService.findAll()); + } + + + @PostMapping + public Result add(@RequestBody Goods goods) { + goodsService.add(goods); + return Result.success(); + } + +} diff --git a/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/mapper/GoodsMapper.java b/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/mapper/GoodsMapper.java new file mode 100644 index 0000000..71aa3c1 --- /dev/null +++ b/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/mapper/GoodsMapper.java @@ -0,0 +1,32 @@ +package com.bwie.goods.mapper; + +import com.bwie.common.domain.Goods; +import com.bwie.common.domain.dto.GoodsQueryDTO; +import com.bwie.common.domain.vo.GoodsVO; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/18 + */ +@Mapper +public interface GoodsMapper { + /** + * 查询商品信息 + * @param goodsQueryDTO + * @return + */ + List list(GoodsQueryDTO goodsQueryDTO); + + + List findAll(); + + + void add(Goods goods); + + GoodsVO detail(Long id); +} diff --git a/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/service/GoodsService.java b/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/service/GoodsService.java new file mode 100644 index 0000000..b9ee907 --- /dev/null +++ b/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/service/GoodsService.java @@ -0,0 +1,30 @@ +package com.bwie.goods.service; + +import com.bwie.common.domain.Goods; +import com.bwie.common.domain.dto.GoodsQueryDTO; +import com.bwie.common.domain.vo.GoodsVO; +import com.bwie.common.result.PageResult; +import com.bwie.common.result.Result; + +import java.util.List; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/18 + */ +public interface GoodsService { + /** + * 查询商品列表 + * @param goodsQueryDTO + * @return + */ + Result> list(GoodsQueryDTO goodsQueryDTO); + + List findAll(); + + void add(Goods goods); + + GoodsVO detail(Long id); +} diff --git a/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/service/impl/GoodsServiceImpl.java b/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/service/impl/GoodsServiceImpl.java new file mode 100644 index 0000000..40912a1 --- /dev/null +++ b/bwie-modules/bwie-goods/src/main/java/com/bwie/goods/service/impl/GoodsServiceImpl.java @@ -0,0 +1,99 @@ +package com.bwie.goods.service.impl; + +import com.alibaba.fastjson.JSONObject; +import com.bwie.common.constants.MQQueueNameConstants; +import com.bwie.common.constants.RoleConstants; +import com.bwie.common.constants.TokenConstants; +import com.bwie.common.domain.Goods; +import com.bwie.common.domain.SysUser; +import com.bwie.common.domain.dto.GoodsQueryDTO; +import com.bwie.common.domain.vo.GoodsVO; +import com.bwie.common.result.PageResult; +import com.bwie.common.result.Result; +import com.bwie.common.utils.JwtUtils; +import com.bwie.goods.mapper.GoodsMapper; +import com.bwie.goods.service.GoodsService; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.UUID; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/18 + */ +@Service +public class GoodsServiceImpl implements GoodsService { + + @Autowired + private GoodsMapper goodsMapper; + + @Autowired + private HttpServletRequest request; + + @Autowired + private RedisTemplate redisTemplate; + + @Autowired + private RabbitTemplate rabbitTemplate; + + @Override + public Result> list(GoodsQueryDTO goodsQueryDTO) { + PageHelper.startPage(goodsQueryDTO.getPageNum(), goodsQueryDTO.getPageSize()); + // 普通用户展示自己管理的仓库信息,管理员登录所有仓库的信息 + // 区分角色 + SysUser sysUser = userInfo(); + if (sysUser.getRole() == RoleConstants.ORDINARY_USERS) { + goodsQueryDTO.setCreateBy(sysUser.getId()); + } + List goodsList = goodsMapper.list(goodsQueryDTO); + PageInfo pageInfo = new PageInfo<>(goodsList); + return PageResult.toResult(pageInfo.getTotal(), goodsList); + } + + @Override + public List findAll() { + return goodsMapper.findAll(); + } + + @Override + public void add(Goods goods) { + goodsMapper.add(goods); + // 查询 + GoodsVO goodsVO = this.detail(goods.getId()); + // 异步 同步 + rabbitTemplate.convertAndSend(MQQueueNameConstants.ADD_GOODS_ES_QUEUE_NAME, goodsVO, message -> { + message.getMessageProperties().setMessageId(UUID.randomUUID().toString()); + return message; + }); + } + + @Override + public GoodsVO detail(Long id) { + return goodsMapper.detail(id); + } + + /** + * 获取当登录用户的信息 + */ + private SysUser userInfo() { + // 获取 请求头中的 token + String token = request.getHeader(TokenConstants.TOKEN); + // 获取 userKey + String userKey = JwtUtils.getUserKey(token); + // 获取redis中的用户的信息 -》 key + String userJson = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey); + // 反序列化 + return JSONObject.parseObject(userJson, SysUser.class); + } + + +} diff --git a/bwie-modules/bwie-goods/src/main/resources/bootstrap.yml b/bwie-modules/bwie-goods/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..b6a193e --- /dev/null +++ b/bwie-modules/bwie-goods/src/main/resources/bootstrap.yml @@ -0,0 +1,29 @@ +# Tomcat +server: + port: 9003 +# Spring +spring: + main: + allow-circular-references: true # 允许循环依赖 + jackson: # json 序列化 和 返序列化 转换 + date-format: yyyy-MM-dd HH:mm:ss + time-zone: GMT+8 + application: + # 应用名称 + name: bwie-goods + profiles: + # 环境配置 + active: dev + cloud: + nacos: + discovery: + # 服务注册地址 + server-addr: 123.249.113.136:8848 + config: + # 配置中心地址 + server-addr: 123.249.113.136:8848 + # 配置文件格式 + file-extension: yml + # 共享配置 + shared-configs: + - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} diff --git a/bwie-modules/bwie-goods/src/main/resources/mapper/GoodsMapper.xml b/bwie-modules/bwie-goods/src/main/resources/mapper/GoodsMapper.xml new file mode 100644 index 0000000..fc72998 --- /dev/null +++ b/bwie-modules/bwie-goods/src/main/resources/mapper/GoodsMapper.xml @@ -0,0 +1,29 @@ + + + + + INSERT INTO tb_goods(goods_name, price, create_by, type_id) VALUES (#{goodsName}, #{price}, #{createBy}, #{typeId}) + + + + + diff --git a/bwie-modules/bwie-kafka/pom.xml b/bwie-modules/bwie-kafka/pom.xml new file mode 100644 index 0000000..487940c --- /dev/null +++ b/bwie-modules/bwie-kafka/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + com.bwie + bwie-modules + 1.0-SNAPSHOT + + + bwie-kafka + + + + com.bwie + bwie-common + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.kafka + spring-kafka + + + + diff --git a/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/KafkaApplication.java b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/KafkaApplication.java new file mode 100644 index 0000000..c1a5687 --- /dev/null +++ b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/KafkaApplication.java @@ -0,0 +1,19 @@ +package com.bwie.kafka; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/11/2 + */ +@SpringBootApplication +public class KafkaApplication { + + public static void main(String[] args) { + SpringApplication.run(KafkaApplication.class); + } + +} diff --git a/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/KafkaConsumerConfig.java b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/KafkaConsumerConfig.java new file mode 100644 index 0000000..a7ff328 --- /dev/null +++ b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/KafkaConsumerConfig.java @@ -0,0 +1,108 @@ +package com.bwie.kafka.config; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.config.KafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.listener.ConcurrentMessageListenerContainer; +import org.springframework.kafka.listener.ContainerProperties; +import org.springframework.kafka.support.serializer.JsonDeserializer; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author 徐一杰 + * @date 2022/10/31 18:05 + * kafka配置,也可以写在yml,这个文件会覆盖yml + */ +@SpringBootConfiguration +public class KafkaConsumerConfig { + + @Value("${spring.kafka.consumer.bootstrap-servers}") + private String bootstrapServers; + + @Value("${spring.kafka.consumer.group-id}") + private String groupId; + + @Value("${spring.kafka.consumer.enable-auto-commit}") + private boolean enableAutoCommit; + + @Value("${spring.kafka.properties.session.timeout.ms}") + private String sessionTimeout; + + @Value("${spring.kafka.properties.max.poll.interval.ms}") + private String maxPollIntervalTime; + + @Value("${spring.kafka.consumer.max-poll-records}") + private String maxPollRecords; + @Value("${spring.kafka.consumer.auto-offset-reset}") + private String autoOffsetReset; + @Value("${spring.kafka.listener.concurrency}") + private Integer concurrency; + @Value("${spring.kafka.listener.missing-topics-fatal}") + private boolean missingTopicsFatal; + @Value("${spring.kafka.listener.poll-timeout}") + private long pollTimeout; + + @Bean + public Map consumerConfigs() { + + Map propsMap = new HashMap<>(16); + propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); + //是否自动提交偏移量,默认值是true,为了避免出现重复数据和数据丢失,可以把它设置为false,然后手动提交偏移量 + propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, enableAutoCommit); + //自动提交的时间间隔,自动提交开启时生效 + propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "2000"); + //该属性指定了消费者在读取一个没有偏移量的分区或者偏移量无效的情况下该作何处理: + //earliest:当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,从头开始消费分区的记录 + //latest:当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,消费新产生的该分区下的数据(在消费者启动之后生成的记录) + //none:当各分区都存在已提交的offset时,从提交的offset开始消费;只要有一个分区不存在已提交的offset,则抛出异常 + propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset); + //两次poll之间的最大间隔,默认值为5分钟。如果超过这个间隔会触发reBalance + propsMap.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, maxPollIntervalTime); + //这个参数定义了poll方法最多可以拉取多少条消息,默认值为500。如果在拉取消息的时候新消息不足500条,那有多少返回多少;如果超过500条,每次只返回500。 + //这个默认值在有些场景下太大,有些场景很难保证能够在5min内处理完500条消息, + //如果消费者无法在5分钟内处理完500条消息的话就会触发reBalance, + //然后这批消息会被分配到另一个消费者中,还是会处理不完,这样这批消息就永远也处理不完。 + //要避免出现上述问题,提前评估好处理一条消息最长需要多少时间,然后覆盖默认的max.poll.records参数 + //注:需要开启BatchListener批量监听才会生效,如果不开启BatchListener则不会出现reBalance情况 + propsMap.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords); + //当broker多久没有收到consumer的心跳请求后就触发reBalance,默认值是10s + propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, sessionTimeout); + //序列化(建议使用Json,这种序列化方式可以无需额外配置传输实体类) + propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); + propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); + return propsMap; + } + + @Bean + public ConsumerFactory consumerFactory() { + // 配置消费者的 Json 反序列化的可信赖包,反序列化实体类需要 + try (JsonDeserializer deserializer = new JsonDeserializer<>()) { + deserializer.trustedPackages("*"); + return new DefaultKafkaConsumerFactory<>(consumerConfigs(), new JsonDeserializer<>(), deserializer); + } + } + + @Bean + public KafkaListenerContainerFactory> kafkaListenerContainerFactory() { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory()); + //在侦听器容器中运行的线程数,一般设置为 机器数*分区数 + factory.setConcurrency(concurrency); + //消费监听接口监听的主题不存在时,默认会报错,所以设置为false忽略错误 + factory.setMissingTopicsFatal(missingTopicsFatal); + // 自动提交关闭,需要设置手动消息确认 + factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE); + factory.getContainerProperties().setPollTimeout(pollTimeout); + // 设置为批量监听,需要用List接收 + // factory.setBatchListener(true); + return factory; + } +} diff --git a/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/KafkaProviderConfig.java b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/KafkaProviderConfig.java new file mode 100644 index 0000000..4ee9d1d --- /dev/null +++ b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/KafkaProviderConfig.java @@ -0,0 +1,84 @@ +package com.bwie.kafka.config; + +import org.apache.kafka.clients.producer.ProducerConfig; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; +import org.springframework.kafka.transaction.KafkaTransactionManager; +import org.springframework.kafka.support.serializer.JsonSerializer; + +import java.util.HashMap; +import java.util.Map; + +/** + * 消息生产者对象的配置 构建 KafkaTemplate 设置发送消息带事务 + */ +@SpringBootConfiguration +public class KafkaProviderConfig { + + @Value("${spring.kafka.producer.bootstrap-servers}") + private String bootstrapServers; + @Value("${spring.kafka.producer.transaction-id-prefix}") + private String transactionIdPrefix; + @Value("${spring.kafka.producer.acks}") + private String acks; + @Value("${spring.kafka.producer.retries}") + private String retries; + @Value("${spring.kafka.producer.batch-size}") + private String batchSize; + @Value("${spring.kafka.producer.buffer-memory}") + private String bufferMemory; + + @Bean + public Map producerConfigs() { + Map props = new HashMap<>(16); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + //acks=0 : 生产者在成功写入消息之前不会等待任何来自服务器的响应。 + //acks=1 : 只要集群的首领节点收到消息,生产者就会收到一个来自服务器成功响应。 + //acks=all :只有当所有参与复制的节点全部收到消息时,生产者才会收到一个来自服务器的成功响应。 + //开启事务必须设为all + props.put(ProducerConfig.ACKS_CONFIG, acks); + //发生错误后,消息重发的次数,开启事务必须大于0 + props.put(ProducerConfig.RETRIES_CONFIG, retries); + //当多个消息发送到相同分区时,生产者会将消息打包到一起,以减少请求交互. 而不是一条条发送 + //批次的大小可以通过batch.size 参数设置.默认是16KB + //较小的批次大小有可能降低吞吐量(批次大小为0则完全禁用批处理)。 + //比如说,kafka里的消息5秒钟Batch才凑满了16KB,才能发送出去。那这些消息的延迟就是5秒钟 + //实测batchSize这个参数没有用 + props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize); + //有的时刻消息比较少,过了很久,比如5min也没有凑够16KB,这样延时就很大,所以需要一个参数. 再设置一个时间,到了这个时间, + //即使数据没达到16KB,也将这个批次发送出去 + props.put(ProducerConfig.LINGER_MS_CONFIG, "5000"); + //生产者内存缓冲区的大小 + props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory); + //反序列化,和生产者的序列化方式对应 + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); + return props; + } + + @Bean + public ProducerFactory producerFactory() { + DefaultKafkaProducerFactory factory = new DefaultKafkaProducerFactory<>(producerConfigs()); + //开启事务,会导致 LINGER_MS_CONFIG 配置失效 + factory.setTransactionIdPrefix(transactionIdPrefix); + return factory; + } + + @Bean + public KafkaTransactionManager kafkaTransactionManager(ProducerFactory producerFactory) { + return new KafkaTransactionManager<>(producerFactory); + } + + /** + * 构建 kafkaTemplate + * @return + */ + @Bean + public KafkaTemplate kafkaTemplate() { + return new KafkaTemplate<>(producerFactory()); + } +} diff --git a/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/KafkaSendResultHandler.java b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/KafkaSendResultHandler.java new file mode 100644 index 0000000..a60b0eb --- /dev/null +++ b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/KafkaSendResultHandler.java @@ -0,0 +1,38 @@ +package com.bwie.kafka.config; + +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.clients.producer.RecordMetadata; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.support.ProducerListener; +import org.springframework.lang.Nullable; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +/** + * @author 徐一杰 + * @date 2022/10/31 15:41 + * kafka消息发送回调 + */ +@Component +public class KafkaSendResultHandler implements ProducerListener { + + @Autowired + private KafkaTemplate kafkaTemplate; + + @PostConstruct + public void init() { + this.kafkaTemplate.setProducerListener(this); + } + + @Override + public void onSuccess(ProducerRecord producerRecord, RecordMetadata recordMetadata) { + System.out.println("消息发送成功:" + producerRecord.toString()); + } + + @Override + public void onError(ProducerRecord producerRecord, @Nullable RecordMetadata recordMetadata, Exception exception) { + System.out.println("消息发送失败:" + producerRecord.toString() + exception.getMessage()); + } +} diff --git a/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/MyKafkaListenerErrorHandler.java b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/MyKafkaListenerErrorHandler.java new file mode 100644 index 0000000..e5e82ce --- /dev/null +++ b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/config/MyKafkaListenerErrorHandler.java @@ -0,0 +1,34 @@ +package com.bwie.kafka.config; + +import org.apache.kafka.clients.consumer.Consumer; +import org.springframework.kafka.listener.KafkaListenerErrorHandler; +import org.springframework.kafka.listener.ListenerExecutionFailedException; +import org.springframework.lang.NonNull; +import org.springframework.messaging.Message; +import org.springframework.stereotype.Component; + +/** + * @author 徐一杰 + * @date 2022/10/31 15:27 + * 异常处理 + */ +@Component +public class MyKafkaListenerErrorHandler implements KafkaListenerErrorHandler { + + @Override + @NonNull + public Object handleError(@NonNull Message message, @NonNull ListenerExecutionFailedException exception) { + return new Object(); + } + + @Override + @NonNull + public Object handleError(@NonNull Message message, @NonNull ListenerExecutionFailedException exception, + Consumer consumer) { + System.out.println("消息详情:" + message); + System.out.println("异常信息::" + exception); + System.out.println("消费者详情::" + consumer.groupMetadata()); + System.out.println("监听主题::" + consumer.listTopics()); + return KafkaListenerErrorHandler.super.handleError(message, exception, consumer); + } +} diff --git a/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/consumer/HelloWorldKafkaConsumer.java b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/consumer/HelloWorldKafkaConsumer.java new file mode 100644 index 0000000..578d24b --- /dev/null +++ b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/consumer/HelloWorldKafkaConsumer.java @@ -0,0 +1,40 @@ +package com.bwie.kafka.consumer; + +import lombok.extern.log4j.Log4j2; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.support.Acknowledgment; +import org.springframework.stereotype.Component; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/11/2 + */ +@Component +@Log4j2 +public class HelloWorldKafkaConsumer { + +// @KafkaListener(topics = { "hw-topic" }) +// public void helloWorldKafkaConsumer(ConsumerRecord record) { +// String key = record.key(); +// String value = record.value(); +// log.info("消息的消费者接收到消息,消息的key:{},value:{}", key, value); +// } + + @KafkaListener(topics = {"topic1", "topic2"}, + containerFactory = "kafkaListenerContainerFactory", + errorHandler = "myKafkaListenerErrorHandler") + public void helloWorldKafkaConsumer(ConsumerRecord record, + Acknowledgment acknowledgment) { + String key = record.key(); + String value = record.value(); + log.info("消息的消费者接收到消息,消息的key:{},value:{}", key, value); + // 手动确认 + acknowledgment.acknowledge(); + } + + +} diff --git a/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/consumer/KafkaConsumerQuickStart.java b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/consumer/KafkaConsumerQuickStart.java new file mode 100644 index 0000000..ab2acb6 --- /dev/null +++ b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/consumer/KafkaConsumerQuickStart.java @@ -0,0 +1,46 @@ +package com.bwie.kafka.consumer; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.serialization.StringDeserializer; + +import java.time.Duration; +import java.util.Collections; +import java.util.Properties; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/11/2 + */ +public class KafkaConsumerQuickStart { + + public static void main(String[] args) { + // 创建 properties 对象 配置 kafka消费者的配置信息 + Properties properties = new Properties(); + properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "123.249.113.136:9092"); + // 设置 键值的反序列化方式 + properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + // 配置 分组 *** + properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "bw2"); + + // 创建 kafka 消息消费者对象 + KafkaConsumer kafkaConsumer = new KafkaConsumer(properties); + // 订阅主题 + kafkaConsumer.subscribe(Collections.singleton("bwie-topic")); + while (true) { + // 拉取消息 + ConsumerRecords records = kafkaConsumer.poll(Duration.ofMillis(2000)); + // 遍历 + records.forEach(record -> { + String key = record.key(); + String value = record.value(); + System.out.println("消息者消息成功,消息的key:" + key + ",value:" + value); + }); + } + } + +} diff --git a/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/controller/HelloWorldKafkaController.java b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/controller/HelloWorldKafkaController.java new file mode 100644 index 0000000..d55471e --- /dev/null +++ b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/controller/HelloWorldKafkaController.java @@ -0,0 +1,63 @@ +package com.bwie.kafka.controller; + +import org.apache.kafka.clients.producer.ProducerRecord; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.kafka.support.SendResult; +import org.springframework.messaging.MessageHeaders; +import org.springframework.messaging.support.GenericMessage; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.concurrent.ListenableFuture; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/11/2 + */ +@RestController +@RequestMapping("kafka") +public class HelloWorldKafkaController { + +// @Autowired +// private KafkaTemplate kafkaTemplate; +// +// @GetMapping("send/message") +// public String sendMessage() { +// // 发送消息 +// kafkaTemplate.send("hw-topic", "hello", "kafka"); +//// listenableFuture.addCallback(result -> { +//// }, ex -> { +//// }); +// return "ok"; +// } + + @Autowired + private KafkaTemplate kafkaTemplate; + + @GetMapping("send/message") + @Transactional + public String sendMessage() { +// ProducerRecord producerRecord = new ProducerRecord("topic1", "hello", "kafka"); + kafkaTemplate.send("topic1", "hello", "kafka"); + + //使用 Message发送消息 + Map map = new HashMap<>(); + map.put(KafkaHeaders.TOPIC, "topic1"); + map.put(KafkaHeaders.PARTITION_ID, 0); + map.put(KafkaHeaders.MESSAGE_KEY, "0"); + GenericMessage message = new GenericMessage<>("use Message to send message", new MessageHeaders(map)); + kafkaTemplate.send(message); + + return "ok"; + } + + +} diff --git a/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/producer/KafkaProducerQuickStart.java b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/producer/KafkaProducerQuickStart.java new file mode 100644 index 0000000..45bd5ae --- /dev/null +++ b/bwie-modules/bwie-kafka/src/main/java/com/bwie/kafka/producer/KafkaProducerQuickStart.java @@ -0,0 +1,69 @@ +package com.bwie.kafka.producer; + +import org.apache.kafka.clients.producer.*; +import org.apache.kafka.common.serialization.StringSerializer; + +import java.util.Properties; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/11/2 + */ +public class KafkaProducerQuickStart { + + + /** + * + * 消息队列模式: + * 点对点: 1 : 1 + * + * 发布订阅: 1 : N + * + * + * @param args + */ + public static void main(String[] args) { + // 发送消息 Kafka + // 用来配置 kafka消息生产者对象的配置信息 + Properties properties = new Properties(); + // 配置 host + properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "123.249.113.136:9092"); + // 配置 键值的序列化方式 + properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + // 配置消息的确认 + properties.setProperty(ProducerConfig.ACKS_CONFIG, "all"); + // 设置重试次数 + properties.setProperty(ProducerConfig.RETRIES_CONFIG, "3"); + // 消息压缩 + properties.setProperty(ProducerConfig.COMPRESSION_TYPE_CONFIG, "gzip"); + // 创建消息生产者对象 + KafkaProducer kafkaProducer = new KafkaProducer(properties); + + // 发送消息 + // 创建 消息记录 + ProducerRecord producerRecord = new ProducerRecord("bwie-topic", "key", "hello world"); +// kafkaProducer.send(producerRecord); + + // 异步发送 + kafkaProducer.send(producerRecord, (metadata, exception) -> { + if (exception == null) { + // 获取消息发送的分区 + int partition = metadata.partition(); + // 消息的偏移量 + long offset = metadata.offset(); + // 主题 + String topic = metadata.topic(); + System.out.println("发送成功,消息的分区:" + partition + ",消息的偏移量:" + offset + ",主题:" + topic); + } else { + System.out.println("发送失败,异常信息:" + exception); + } + }); + + // 关闭 kafkaProducer + kafkaProducer.close(); + } + +} diff --git a/bwie-modules/bwie-kafka/src/main/resources/bootstrap.yml b/bwie-modules/bwie-kafka/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..fa106e3 --- /dev/null +++ b/bwie-modules/bwie-kafka/src/main/resources/bootstrap.yml @@ -0,0 +1,102 @@ +# Tomcat +server: + port: 9009 +# Spring +spring: + kafka: + producer: + # Kafka服务器 + bootstrap-servers: 123.249.113.136:9092 + # 开启事务,必须在开启了事务的方法中发送,否则报错 + transaction-id-prefix: kafkaTx- + # 发生错误后,消息重发的次数,开启事务必须设置大于0。 + retries: 3 + # acks=0 : 生产者在成功写入消息之前不会等待任何来自服务器的响应。 + # acks=1 : 只要集群的首领节点收到消息,生产者就会收到一个来自服务器成功响应。 + # acks=all :只有当所有参与复制的节点全部收到消息时,生产者才会收到一个来自服务器的成功响应。 + # 开启事务时,必须设置为all + acks: all + # 当有多个消息需要被发送到同一个分区时,生产者会把它们放在同一个批次里。该参数指定了一个批次可以使用的内存大小,按照字节数计算。 + batch-size: 16384 + # 生产者内存缓冲区的大小。 + buffer-memory: 1024000 + # 键的序列化方式 + key-serializer: org.springframework.kafka.support.serializer.JsonSerializer + # 值的序列化方式(建议使用Json,这种序列化方式可以无需额外配置传输实体类) + value-serializer: org.springframework.kafka.support.serializer.JsonSerializer + + consumer: + # Kafka服务器 + bootstrap-servers: 123.249.113.136:9092 + group-id: firstGroup + # 自动提交的时间间隔 在spring boot 2.X 版本中这里采用的是值的类型为Duration 需要符合特定的格式,如1S,1M,2H,5D + #auto-commit-interval: 2s + # 该属性指定了消费者在读取一个没有偏移量的分区或者偏移量无效的情况下该作何处理: + # earliest:当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,从头开始消费分区的记录 + # latest:当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,消费新产生的该分区下的数据(在消费者启动之后生成的记录) + # none:当各分区都存在已提交的offset时,从提交的offset开始消费;只要有一个分区不存在已提交的offset,则抛出异常 + auto-offset-reset: latest + # 是否自动提交偏移量,默认值是true,为了避免出现重复数据和数据丢失,可以把它设置为false,然后手动提交偏移量 + enable-auto-commit: false + # 键的反序列化方式 + #key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + key-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer + # 值的反序列化方式(建议使用Json,这种序列化方式可以无需额外配置传输实体类) + value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer + # 配置消费者的 Json 反序列化的可信赖包,反序列化实体类需要 + properties: + spring: + json: + trusted: + packages: "*" + # 这个参数定义了poll方法最多可以拉取多少条消息,默认值为500。如果在拉取消息的时候新消息不足500条,那有多少返回多少;如果超过500条,每次只返回500。 + # 这个默认值在有些场景下太大,有些场景很难保证能够在5min内处理完500条消息, + # 如果消费者无法在5分钟内处理完500条消息的话就会触发reBalance, + # 然后这批消息会被分配到另一个消费者中,还是会处理不完,这样这批消息就永远也处理不完。 + # 要避免出现上述问题,提前评估好处理一条消息最长需要多少时间,然后覆盖默认的max.poll.records参数 + # 注:需要开启BatchListener批量监听才会生效,如果不开启BatchListener则不会出现reBalance情况 + max-poll-records: 3 + properties: + # 两次poll之间的最大间隔,默认值为5分钟。如果超过这个间隔会触发reBalance + max: + poll: + interval: + ms: 600000 + # 当broker多久没有收到consumer的心跳请求后就触发reBalance,默认值是10s + session: + timeout: + ms: 10000 + listener: + # 在侦听器容器中运行的线程数,一般设置为 机器数*分区数 + concurrency: 4 + # 自动提交关闭,需要设置手动消息确认 + ack-mode: manual_immediate + # 消费监听接口监听的主题不存在时,默认会报错,所以设置为false忽略错误 + missing-topics-fatal: false + # 两次poll之间的最大间隔,默认值为5分钟。如果超过这个间隔会触发reBalance + poll-timeout: 600000 + main: + allow-circular-references: true # 允许循环依赖 + jackson: # json 序列化 和 返序列化 转换 + date-format: yyyy-MM-dd HH:mm:ss + time-zone: GMT+8 + application: + # 应用名称 + name: bwie-kafka + profiles: + # 环境配置 + active: dev + cloud: + nacos: + discovery: + # 服务注册地址 + server-addr: 123.249.113.136:8848 + config: + # 配置中心地址 + server-addr: 123.249.113.136:8848 + namespace: a9b66e92-e507-47ba-9674-6f939f793aca + # 配置文件格式 + file-extension: yml + # 共享配置 + shared-configs: + - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} diff --git a/bwie-modules/bwie-rabbitmq/pom.xml b/bwie-modules/bwie-rabbitmq/pom.xml new file mode 100644 index 0000000..c0a1a6a --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + com.bwie + bwie-modules + 1.0-SNAPSHOT + + + bwie-rabbitmq + + + + com.bwie + bwie-common + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-amqp + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + + diff --git a/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/RabbitMQApplication.java b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/RabbitMQApplication.java new file mode 100644 index 0000000..b4e1e79 --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/RabbitMQApplication.java @@ -0,0 +1,32 @@ +package com.bwie.mq; + +import com.rabbitmq.client.AMQP; +import org.springframework.amqp.core.Queue; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/20 + */ +@SpringBootApplication +public class RabbitMQApplication { + + public static void main(String[] args) { + SpringApplication.run(RabbitMQApplication.class); + } + +// /** +// * 初始化队列 +// * @return +// */ +// @Bean +// public Queue initQueue() { +// return new Queue("hello_world_queue", true); +// } + + +} diff --git a/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/config/ConfirmCallbackConfig.java b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/config/ConfirmCallbackConfig.java new file mode 100644 index 0000000..d82f690 --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/config/ConfirmCallbackConfig.java @@ -0,0 +1,48 @@ +package com.bwie.mq.config; + +import org.springframework.amqp.rabbit.connection.CorrelationData; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +/** + * @ClassName: + * @Description: 消息发送到 broker的确认 重写 confirm 方法 + * @Author: zhuwenqiang + * @Date: 2023/10/23 + */ +@Component +public class ConfirmCallbackConfig implements RabbitTemplate.ConfirmCallback { + + @Autowired + private RabbitTemplate rabbitTemplate; + + /** + * 当前类被初始化的时候执行的方法 + * + */ + @PostConstruct + public void init() { + // 设置 rabbitTemplate 的消息发送到交换机确认 + rabbitTemplate.setConfirmCallback(this); + } + + /** + * 消息发送到交换机 无论成功或者失败 都会执行 + * + * @param correlationData correlation data for the callback. + * @param ack true for ack, false for nack true 成功 false 失败 + * @param cause An optional cause, for nack, when available, otherwise null. + */ + @Override + public void confirm(CorrelationData correlationData, boolean ack, String cause) { + if (ack) { + System.out.println("消息发送到broker成功!"); + } else { + System.out.println("消息发送到broker失败,失败的原因是:" + cause); + } + } + +} diff --git a/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/config/RabbitmqConfig.java b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/config/RabbitmqConfig.java new file mode 100644 index 0000000..d7e7f0e --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/config/RabbitmqConfig.java @@ -0,0 +1,15 @@ +package com.bwie.mq.config; + +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; + +@Configuration +public class RabbitmqConfig { + // 消息转换配置 SimpleMessageConverter String byte[] serializable + @Bean + public MessageConverter jsonMessageConverter() { + return new Jackson2JsonMessageConverter(); + } +} diff --git a/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/config/ReturnsCallbackConfig.java b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/config/ReturnsCallbackConfig.java new file mode 100644 index 0000000..8b06481 --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/config/ReturnsCallbackConfig.java @@ -0,0 +1,40 @@ +package com.bwie.mq.config; + +import org.springframework.amqp.core.ReturnedMessage; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +/** + * @ClassName: + * @Description: 消息发送到队列的确认 + * @Author: zhuwenqiang + * @Date: 2023/10/23 + */ +@Component +public class ReturnsCallbackConfig implements RabbitTemplate.ReturnsCallback { + + @Autowired + private RabbitTemplate rabbitTemplate; + + @PostConstruct + public void init() { + rabbitTemplate.setReturnsCallback(this); + } + + /** + * 只有发送到队列失败才会执行 + * + * @param returnedMessage the returned message and metadata. + */ + @Override + public void returnedMessage(ReturnedMessage returnedMessage) { + System.out.println("消息" + returnedMessage.getMessage().toString() + + "被交换机" + returnedMessage.getExchange() + "回退!" + + "退回原因为:" + returnedMessage.getReplyText()); + // TODO 补偿 可以再发 做日志记录 + } + +} diff --git a/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/HelloWorldConsumer.java b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/HelloWorldConsumer.java new file mode 100644 index 0000000..7e4a8a4 --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/HelloWorldConsumer.java @@ -0,0 +1,27 @@ +package com.bwie.mq.consumer; + +import lombok.extern.log4j.Log4j2; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/20 + */ +@Component +@Log4j2 +public class HelloWorldConsumer { + + /** + * 监听队列 获取消息 消费 + */ +// @RabbitListener(queues = { "hello_world_queue" }) + @RabbitListener(queuesToDeclare = {@Queue("hello_world_queue")}) + public void helloWorldConsumer(String message) { + log.info("hello_world_queue队列消费者接收到了消息,消息内容是:{},消费完毕!", message); + } + +} diff --git a/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/MessageConverterConsumer.java b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/MessageConverterConsumer.java new file mode 100644 index 0000000..4f6dbf3 --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/MessageConverterConsumer.java @@ -0,0 +1,69 @@ +package com.bwie.mq.consumer; + +import com.alibaba.fastjson.JSONObject; +import com.bwie.common.domain.SysUser; +import com.rabbitmq.client.Channel; +import lombok.extern.log4j.Log4j2; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/21 + */ +@Component +@Log4j2 +public class MessageConverterConsumer { + + @Autowired + private RedisTemplate redisTemplate; + + /** + * 消息消费者 + * @param message 发送的消息对象 + * @param sysUser 消息的内容 + * @param channel 通道 + */ + @RabbitListener(queuesToDeclare = {@Queue(name = "test_message_converter_queue")}) + @Transactional // 开启事务管理,确保消息处理成功或回滚。 + public void messageConverterConsumer(Message message, SysUser sysUser, Channel channel) { + // 获取消息的 messageId + String messageId = message.getMessageProperties().getMessageId(); + try { + // 如果添加成功返回 1 失败 0 + Long count = redisTemplate.opsForSet().add("test_message_converter_queue", messageId); + if (count == 1) { + // 正常消费 执行业务逻辑 + log.info("test_message_converter_queue队列消费者1接收到了消息,消息内容是:{},消费完毕!", sysUser); + // 执行业务逻辑的时候 出现了异常 + // 手动确认 + // 第一个参数 : 消息投递序号 + // 第二个参数 : 是否批量确认 true false 如果值是true 表示 将 当前所有消息包括 当前序号的消息全部确认 false 只确认这一条消息 + channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); + } + } catch (IOException e) { + e.printStackTrace(); + redisTemplate.opsForSet().remove("test_message_converter_queue", messageId); + // 回退消息 + // 第一个参数 : 消息投递序号 + // 第二个参数 : 是否批量确认 true false 如果值是true 表示 将 当前所有消息包括 当前序号的消息全部确认 false 只确认这一条消息 + // 第三个参数 : 是否回退到原来的队列 true false 消息丢弃 +// channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true); + try { + channel.basicReject(message.getMessageProperties().getDeliveryTag(), true); + } catch (IOException ex) { + e.printStackTrace(); + } + } + } + +} diff --git a/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/PublishSubscribeConsumer.java b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/PublishSubscribeConsumer.java new file mode 100644 index 0000000..c8fa2fd --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/PublishSubscribeConsumer.java @@ -0,0 +1,37 @@ +package com.bwie.mq.consumer; + +import lombok.extern.log4j.Log4j2; +import org.springframework.amqp.core.ExchangeTypes; +import org.springframework.amqp.rabbit.annotation.Exchange; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.QueueBinding; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/20 + */ +@Component +@Log4j2 +public class PublishSubscribeConsumer { + + /** + * 消费1: 交换机和队列绑定 + * @param message + */ + @RabbitListener(bindings = {@QueueBinding(value = @Queue("pb_sb_queue"), + exchange = @Exchange(value = "publish_subscribe_exchange", type = ExchangeTypes.FANOUT))}) + public void publishSubscribeConsumer(String message) { + log.info("pb_sb_queue队列消费者1接收到了消息,消息内容是:{},消费完毕!", message); + } + + @RabbitListener(bindings = {@QueueBinding(value = @Queue("pb_sb_queue2"), + exchange = @Exchange(value = "publish_subscribe_exchange", type = ExchangeTypes.FANOUT))}) + public void publishSubscribeConsumer2(String message) { + log.info("pb_sb_queue队列消费者2接收到了消息,消息内容是:{},消费完毕!", message); + } + +} diff --git a/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/RoutingConsumer.java b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/RoutingConsumer.java new file mode 100644 index 0000000..d6db7ab --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/RoutingConsumer.java @@ -0,0 +1,42 @@ +package com.bwie.mq.consumer; + +import lombok.extern.log4j.Log4j2; +import org.springframework.amqp.core.ExchangeTypes; +import org.springframework.amqp.rabbit.annotation.Exchange; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.QueueBinding; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/20 + */ +@Component +@Log4j2 +public class RoutingConsumer { + + @RabbitListener(bindings = {@QueueBinding(value = @Queue(name = "routing_queue"), + exchange = @Exchange(name = "routing_exchange", type = ExchangeTypes.DIRECT), + key = { "aa", "bb", "error" })}) + public void routingConsumer(String message) { + log.info("routing_queue队列消费者1接收到了消息,消息内容是:{},消费完毕!", message); + } + + @RabbitListener(bindings = {@QueueBinding(value = @Queue(name = "routing_queue2"), + exchange = @Exchange(name = "routing_exchange", type = ExchangeTypes.DIRECT), + key = { "bb", "error" })}) + public void routingConsumer2(String message) { + log.info("routing_queue队列消费者2接收到了消息,消息内容是:{},消费完毕!", message); + } + + @RabbitListener(bindings = {@QueueBinding(value = @Queue(name = "routing_queue3"), + exchange = @Exchange(name = "routing_exchange", type = ExchangeTypes.DIRECT), + key = { "aac", "cc", "error" })}) + public void routingConsumer3(String message) { + log.info("routing_queue队列消费者3接收到了消息,消息内容是:{},消费完毕!", message); + } + +} diff --git a/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/TopicConsumer.java b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/TopicConsumer.java new file mode 100644 index 0000000..ae249ab --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/TopicConsumer.java @@ -0,0 +1,34 @@ +package com.bwie.mq.consumer; + +import lombok.extern.log4j.Log4j2; +import org.springframework.amqp.core.ExchangeTypes; +import org.springframework.amqp.rabbit.annotation.Exchange; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.QueueBinding; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/21 + */ +@Component +@Log4j2 +public class TopicConsumer { + + @RabbitListener(bindings = { @QueueBinding(value = @Queue(name = "topic_queue"), + exchange = @Exchange(name = "topic_exchange", type = ExchangeTypes.TOPIC), + key = { "*.name.*", "age.#" })}) + public void topicConsumer(String message) { + log.info("topic_queue队列消费者1接收到了消息,消息内容是:{},消费完毕!", message); + } + + @RabbitListener(bindings = { @QueueBinding(value = @Queue(name = "topic_queue2"), + exchange = @Exchange(name = "topic_exchange", type = ExchangeTypes.TOPIC), + key = { "user.name", "user.name.age" })}) + public void topicConsumer2(String message) { + log.info("topic_queue2队列消费者2接收到了消息,消息内容是:{},消费完毕!", message); + } +} diff --git a/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/WorkQueuesConsumer.java b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/WorkQueuesConsumer.java new file mode 100644 index 0000000..d53debf --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/consumer/WorkQueuesConsumer.java @@ -0,0 +1,31 @@ +package com.bwie.mq.consumer; + +import lombok.extern.java.Log; +import lombok.extern.log4j.Log4j2; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/20 + */ +@Component +@Log4j2 +public class WorkQueuesConsumer { + + @RabbitListener(queuesToDeclare = {@Queue("work_queues_queue")}) + public void workQueuesConsumer(String message) throws InterruptedException { + Thread.sleep(200); + log.info("work_queues_queue队列消费者1接收到了消息,消息内容是:{},消费完毕!", message); + } + + @RabbitListener(queuesToDeclare = {@Queue("work_queues_queue")}) + public void workQueuesConsumer2(String message) throws InterruptedException { + Thread.sleep(400); + log.info("work_queues_queue队列消费2者接收到了消息,消息内容是:{},消费完毕!", message); + } + +} diff --git a/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/producer/RabbitMQController.java b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/producer/RabbitMQController.java new file mode 100644 index 0000000..f96feff --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/src/main/java/com/bwie/mq/producer/RabbitMQController.java @@ -0,0 +1,111 @@ +package com.bwie.mq.producer; + +import com.alibaba.fastjson.JSONObject; +import com.bwie.common.domain.SysUser; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.UUID; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/20 + */ +@RestController +@RequestMapping("mq") +public class RabbitMQController { + + @Autowired + private RabbitTemplate rabbitTemplate; + + /** + * 发送消息 hello world 一个消息生产者 一个队列 一个消息消费者 + */ + @GetMapping("hello/world") + public String helloWorld() { + // routingKey: 队列名称 + // object : 消息的内容 + rabbitTemplate.convertAndSend("hello_world_queue", "hello world rabbit!"); + return "ok"; + } + + /** + * work queues 工作队列模式 一个消息生产者 一个队列 多个消息消费者 + */ + @GetMapping("work/queues") + public String workQueues() { + // routingKey: 队列名称 + // object : 消息的内容 + for (int i = 1; i <= 10; i++) { + rabbitTemplate.convertAndSend("work_queues_queue", "hello world work!"+i); + } + return "ok"; + } + + /** + * publish/subscribe 发布订阅 + * 特点: fanout 交换机 有多个队列 将消息先发送给交换机,然后交换机会将消息发送给与其绑定的队列 + */ + @GetMapping("publish/subscribe") + public String publishSubScribe() { + // 第一个参数: exchange: 交换机的名称 + // 第二个参数: 交换机与队列的绑定的规则 如果是发布订阅模式则 routingKey写成空字符串,只要绑定就行不要写规则 + // 第三个参数: 消息的内容 + rabbitTemplate.convertAndSend("publish_subscribe_exchange", "", "publish subscribe!"); + return "ok"; + } + + + /** + * routing 路由模型 + * 特点: direct 交换机 有多个队列 将消息先发送给交换机,然后交换机会将消息发送给与其绑定的队列,并且需要满足绑定规则 + */ + @GetMapping("routing") + public String routing() { + // 第一个参数: exchange: 交换机的名称 + // 第二个参数: 绑定规则 名字随意 字符串 + // 第三个参数: 消息的内容 + rabbitTemplate.convertAndSend("routing_exchange", "aa", "publish subscribe!"); + return "ok"; + } + + /** + * topic 主题模型 + * 特点: topic 交换机 有多个队列 将消息先发送给交换机,然后交换机会将消息发送给与其绑定的队列,并且需要满足绑定规则 通配符 + */ + @GetMapping("topic") + public String topic() { + // 第一个参数: exchange: 交换机的名称 + // 第二个参数: 绑定规则 名字随意 字符串 多个单词组成 以. + // 第三个参数: 消息的内容 + rabbitTemplate.convertAndSend("topic_exchange", "age.name.sex", "topic !"); + return "ok"; + } + + + /** + * 发送消息 hello world 一个消息生产者 一个队列 一个消息消费者 + */ + @GetMapping("hello/world2") + public String helloWorld2() { + // routingKey: 队列名称 + // object : 消息的内容 + SysUser sysUser = new SysUser(); + sysUser.setName("张三"); + sysUser.setPassword("123"); + rabbitTemplate.convertAndSend("test_message_converter_queue", sysUser, message -> { + // 设置消息的 messageId + message.getMessageProperties().setMessageId(UUID.randomUUID().toString()); + return message; + }); + return "ok"; + } + + + +} diff --git a/bwie-modules/bwie-rabbitmq/src/main/resources/bootstrap.yml b/bwie-modules/bwie-rabbitmq/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..c671a7b --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/src/main/resources/bootstrap.yml @@ -0,0 +1,45 @@ +# Tomcat +server: + port: 9004 +# Spring +spring: + rabbitmq: + host: 123.249.113.136 + port: 5672 + username: guest + password: guest + virtual-host: / + listener: + simple: + prefetch: 1 # 每次取出来一条消息,消费完毕之后取下一条消费 + acknowledge-mode: manual # 手动确认消费 + retry: # 重试 + enabled: true + # 发送确认配置 开启发送确认 + publisher-confirm-type: correlated # 消息发送到broker确认 + publisher-returns: true # 消息发送到队列确认 + + main: + allow-circular-references: true # 允许循环依赖 + jackson: # json 序列化 和 返序列化 转换 + date-format: yyyy-MM-dd HH:mm:ss + time-zone: GMT+8 + application: + # 应用名称 + name: bwie-rabbitmq + profiles: + # 环境配置 + active: dev + cloud: + nacos: + discovery: + # 服务注册地址 + server-addr: 123.249.113.136:8848 + config: + # 配置中心地址 + server-addr: 123.249.113.136:8848 + # 配置文件格式 + file-extension: yml + # 共享配置 + shared-configs: + - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} diff --git a/bwie-modules/bwie-rabbitmq/笔记.md b/bwie-modules/bwie-rabbitmq/笔记.md new file mode 100644 index 0000000..01b49a6 --- /dev/null +++ b/bwie-modules/bwie-rabbitmq/笔记.md @@ -0,0 +1,79 @@ +1、概念 + a、MQ的使用场景 + (1)、异步 + (2)、解耦 + (3)、流量削峰 + + b、市面上常见的MQ各自的特点、并且如何选择 + (1)、ActiveMQ + 比较老牌、由apache开发的,吞吐量万级,时效性 ms, 停止维护 慢慢淘汰 + (2)、RabbitMQ + erlang 语言开发的 并发较好 吞吐量万级 时效性 us 可用性高 主从 支持语言较多 社区活跃度高 + (3)、RocketMQ + Java 语言开发 吞吐量 10W级别 时效性 ms 可用性非常高 集群 消息可靠性高 可以做到消息的0丢失 + 互联网金融相关的业务 + (4)、Kafka + Scala 和 Java 语言开发 吞吐量 100W级别 时效性 ms 可用性非常高 集群 + 互联网公司产生大量业务数量收集的场景 日志收集分析 + + c、RabbitMQ 交换机 队列 virtualhost channel + (1)、交换机 消息先发送给交换机,交换机在将消息发送给与其绑定的、并且满足routingKey规则 没有存储消息的能力 + 一条消息 可以被多个消费者同时消费 ,如果没有交换机【只有一个队列】,则消息只能被一个消费者消费 + a、发布订阅模式 fanout + b、路由模型 direct + c、主题模型 topic rabbitMQ 自带的 + (2)、 消息的缓冲区 可以存储消息的 + (3)、 virtualhost 类似于网络上的 namespace 命名空间 隔离作用 + 每一个用户都可以创建自己的交换机|队列 通过不同的 virtualhost 来做隔离相互不影响 + 张三: 创建名字为 a 的队列 , 李四 也可以创建名字为 a 的队列 + (4)、 channel: 轻量级的connection对象 ,较少tcp connection 的连接 + +2、springboot工程中 需要 集成 RabbitMQ [amqp] 高级消息队列协议 + a 引入依赖 + + spring-boot-starter-amqp + b 配置 + 默认值 默认连接的本机 + spring: + rabbitmq: + host: + port: 5672 + username: guest + password: guest + virtual-host: / + c 注入 RabbitTemplate + d 发送消息 + rabbitTemplate.convertAndSend() + e 监听队列 消息消息 + @RabbitListener(queues = {"队列名称",".."}) + 自己构建队列 配置类 new Queue("队列名称", true) + @RabbitListener(queuesToDeclare = { @Queue(name = "队列名称") }) + +队列模式: +(1) hello world + 一个消息生产者 一个队列 一个消费者 + +(2) work queues + 一个消息生产者 一个队列 多个消费者 默认公平消费 配置多劳多得 + + rabbitTemplate.convertAndSend("队列名称", "消息内容") +spring: + rabbitmq: + host: + port: 5672 + username: guest + password: guest + virtual-host: / + listener: + simple: + prefetch: 1 +(3) 发布订阅 publish|subscribe + 一个消息生产者 交换机 多个队列 多个消费者 + routingKey 不需要写规则 只要绑定就行 + rabbitTemplate.convertAndSend("队列名称", "", "消息内容") + @RabbitListener(bindings={ @QueueBindings(value=@Queue(name=""), exchange=@Exchange(name="", type="类型")) }) + + + + + diff --git a/bwie-modules/bwie-sms/pom.xml b/bwie-modules/bwie-sms/pom.xml new file mode 100644 index 0000000..a76342d --- /dev/null +++ b/bwie-modules/bwie-sms/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + + com.bwie + bwie-modules + 1.0-SNAPSHOT + + + bwie-sms + + + + com.bwie + bwie-common + + + org.springframework.boot + spring-boot-starter-web + + + + diff --git a/bwie-modules/bwie-sms/src/main/java/com/bwie/sms/SmsApplication.java b/bwie-modules/bwie-sms/src/main/java/com/bwie/sms/SmsApplication.java new file mode 100644 index 0000000..06eb7ea --- /dev/null +++ b/bwie-modules/bwie-sms/src/main/java/com/bwie/sms/SmsApplication.java @@ -0,0 +1,19 @@ +package com.bwie.sms; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/25 + */ +@SpringBootApplication +public class SmsApplication { + + public static void main(String[] args) { + SpringApplication.run(SmsApplication.class); + } + +} diff --git a/bwie-modules/bwie-sms/src/main/java/com/bwie/sms/consumer/SendSmsQueueConsumer.java b/bwie-modules/bwie-sms/src/main/java/com/bwie/sms/consumer/SendSmsQueueConsumer.java new file mode 100644 index 0000000..b482321 --- /dev/null +++ b/bwie-modules/bwie-sms/src/main/java/com/bwie/sms/consumer/SendSmsQueueConsumer.java @@ -0,0 +1,77 @@ +package com.bwie.sms.consumer; + +import cn.hutool.core.util.RandomUtil; +import com.alibaba.fastjson.JSONObject; +import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody; +import com.bwie.common.domain.dto.SendSmsDTO; +import com.bwie.common.utils.TelSmsUtils; +import com.rabbitmq.client.Channel; +import lombok.extern.log4j.Log4j2; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.HashMap; +import java.util.concurrent.TimeUnit; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/24 + */ +@Component +@Log4j2 +public class SendSmsQueueConsumer { + + @Autowired + private RedisTemplate redisTemplate; + + @RabbitListener(queuesToDeclare = {@Queue("send_sms_queue")}) + public void sendSmsQueueConsumer(Message message, SendSmsDTO sendSmsDTO, Channel channel) { + log.info("短信队列:{},接收到消息:{},开始消费...", "send_sms_queue", JSONObject.toJSONString(sendSmsDTO)); + long s = System.currentTimeMillis(); + // 获取消息 id + String messageId = message.getMessageProperties().getMessageId(); + try { + // 添加消息id到 redis的set 集合中 + Long count = redisTemplate.opsForSet().add("send_sms_queue", messageId); + if (count == 1) { + String jsonStr = TelSmsUtils.sendSms(sendSmsDTO.getMobile(), new HashMap() {{ + put(sendSmsDTO.getKey(), sendSmsDTO.getValue()); + }}); + // 反序列化 + SendSmsResponseBody sendSmsResponseBody = JSONObject.parseObject(jsonStr, SendSmsResponseBody.class); + if (!"OK".equals(sendSmsResponseBody.getCode())) { + TelSmsUtils.sendSms(sendSmsDTO.getMobile(), new HashMap() {{ + put(sendSmsDTO.getKey(), sendSmsDTO.getValue()); + }}); + } + // 手动确认 + channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); + log.info("短信队列:{},接收到消息:{},消费完成,耗时:{}毫秒!", "send_sms_queue", JSONObject.toJSONString(sendSmsDTO), (System.currentTimeMillis() - s)); + } + } catch (Exception e) { + log.error("短信队列:{},接收到消息:{},消费消息异常,异常信息:{}", "send_sms_queue", JSONObject.toJSONString(sendSmsDTO), e.getMessage()); + // 移除 添加到 redis set 集合中的 messageId + redisTemplate.opsForSet().remove("send_sms_queue", messageId); + // 消息回退到原来的队列 + try { + channel.basicReject(message.getMessageProperties().getDeliveryTag(), true); + } catch (IOException ex) { + log.error("短信队列:{},接收到消息:{},消费回退异常,异常信息:{}", "send_sms_queue", JSONObject.toJSONString(sendSmsDTO), e.getMessage()); + } + } + } + + + public static void main(String[] args) { + System.out.println("\"aaaa\""); + } + + +} diff --git a/bwie-modules/bwie-sms/src/main/resources/bootstrap.yml b/bwie-modules/bwie-sms/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..80e334b --- /dev/null +++ b/bwie-modules/bwie-sms/src/main/resources/bootstrap.yml @@ -0,0 +1,30 @@ +# Tomcat +server: + port: 9006 +# Spring +spring: + main: + allow-circular-references: true # 允许循环依赖 + jackson: # json 序列化 和 返序列化 转换 + date-format: yyyy-MM-dd HH:mm:ss + time-zone: GMT+8 + application: + # 应用名称 + name: bwie-sms + profiles: + # 环境配置 + active: dev + cloud: + nacos: + discovery: + # 服务注册地址 + server-addr: 123.249.113.136:8848 + config: + # 配置中心地址 + server-addr: 123.249.113.136:8848 + namespace: a9b66e92-e507-47ba-9674-6f939f793aca + # 配置文件格式 + file-extension: yml + # 共享配置 + shared-configs: + - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} diff --git a/bwie-modules/bwie-system/pom.xml b/bwie-modules/bwie-system/pom.xml new file mode 100644 index 0000000..907ec4c --- /dev/null +++ b/bwie-modules/bwie-system/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.bwie + bwie-modules + 1.0-SNAPSHOT + + + bwie-system + + + + + com.bwie + bwie-common + + + + org.springframework.boot + spring-boot-starter-web + + + + com.alibaba + druid-spring-boot-starter + 1.2.8 + + + + mysql + mysql-connector-java + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 2.2.2 + + + + com.github.pagehelper + pagehelper-spring-boot-starter + 1.4.1 + + + + diff --git a/bwie-modules/bwie-system/src/main/java/com/bwie/system/SystemApplication.java b/bwie-modules/bwie-system/src/main/java/com/bwie/system/SystemApplication.java new file mode 100644 index 0000000..e1814db --- /dev/null +++ b/bwie-modules/bwie-system/src/main/java/com/bwie/system/SystemApplication.java @@ -0,0 +1,19 @@ +package com.bwie.system; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/17 + */ +@SpringBootApplication +public class SystemApplication { + + public static void main(String[] args) { + SpringApplication.run(SystemApplication.class); + } + +} diff --git a/bwie-modules/bwie-system/src/main/java/com/bwie/system/controller/LoginLogController.java b/bwie-modules/bwie-system/src/main/java/com/bwie/system/controller/LoginLogController.java new file mode 100644 index 0000000..8c628d9 --- /dev/null +++ b/bwie-modules/bwie-system/src/main/java/com/bwie/system/controller/LoginLogController.java @@ -0,0 +1,16 @@ +package com.bwie.system.controller; + +import org.springframework.web.bind.annotation.RestController; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/25 + */ +@RestController +public class LoginLogController { + + + +} diff --git a/bwie-modules/bwie-system/src/main/java/com/bwie/system/controller/SysUserController.java b/bwie-modules/bwie-system/src/main/java/com/bwie/system/controller/SysUserController.java new file mode 100644 index 0000000..1409bdf --- /dev/null +++ b/bwie-modules/bwie-system/src/main/java/com/bwie/system/controller/SysUserController.java @@ -0,0 +1,48 @@ +package com.bwie.system.controller; + +import com.alibaba.fastjson.JSONObject; +import com.bwie.common.domain.SysUser; +import com.bwie.common.result.Result; +import com.bwie.system.service.SysUserService; +import lombok.extern.log4j.Log4j2; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/16 + */ +@RestController +@RequestMapping("sys/user") +@Log4j2 +public class SysUserController { + + @Autowired + private HttpServletRequest request; + + @Autowired + private SysUserService sysUserService; + + /** + * 根据手机号查询用户信息 + */ + @GetMapping("findByTel/{tel}") + public Result findByTel(@PathVariable String tel) { + log.info("功能名称:根据手机号查询系统用户,请求URI:{},请求方式:{},请求参数:{}", request.getRequestURI(), + request.getMethod(), tel); + SysUser sysUser = sysUserService.findByTel(tel); + Result result = Result.success(sysUser); + log.info("功能名称:根据手机号查询系统用户,请求URI:{},请求方式:{},响应结果:{}", request.getRequestURI(), + request.getMethod(), JSONObject.toJSONString(result)); + return result; + } + + +} diff --git a/bwie-modules/bwie-system/src/main/java/com/bwie/system/mapper/SysUserMapper.java b/bwie-modules/bwie-system/src/main/java/com/bwie/system/mapper/SysUserMapper.java new file mode 100644 index 0000000..f4f9843 --- /dev/null +++ b/bwie-modules/bwie-system/src/main/java/com/bwie/system/mapper/SysUserMapper.java @@ -0,0 +1,21 @@ +package com.bwie.system.mapper; + +import com.bwie.common.domain.SysUser; +import org.apache.ibatis.annotations.Mapper; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/16 + */ +@Mapper +public interface SysUserMapper { + + /** + * 根据手机号查询用户信息 + * @param tel + * @return + */ + SysUser findByTel(String tel); +} diff --git a/bwie-modules/bwie-system/src/main/java/com/bwie/system/service/SysUserService.java b/bwie-modules/bwie-system/src/main/java/com/bwie/system/service/SysUserService.java new file mode 100644 index 0000000..5572ccb --- /dev/null +++ b/bwie-modules/bwie-system/src/main/java/com/bwie/system/service/SysUserService.java @@ -0,0 +1,18 @@ +package com.bwie.system.service; + +import com.bwie.common.domain.SysUser; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/16 + */ +public interface SysUserService { + /** + * 根据手机号查询用户信息 + * @param tel + * @return + */ + SysUser findByTel(String tel); +} diff --git a/bwie-modules/bwie-system/src/main/java/com/bwie/system/service/impl/SysUserServiceImpl.java b/bwie-modules/bwie-system/src/main/java/com/bwie/system/service/impl/SysUserServiceImpl.java new file mode 100644 index 0000000..ed2c3dd --- /dev/null +++ b/bwie-modules/bwie-system/src/main/java/com/bwie/system/service/impl/SysUserServiceImpl.java @@ -0,0 +1,25 @@ +package com.bwie.system.service.impl; + +import com.bwie.common.domain.SysUser; +import com.bwie.system.mapper.SysUserMapper; +import com.bwie.system.service.SysUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/16 + */ +@Service +public class SysUserServiceImpl implements SysUserService { + + @Autowired + private SysUserMapper sysUserMapper; + + @Override + public SysUser findByTel(String tel) { + return sysUserMapper.findByTel(tel); + } +} diff --git a/bwie-modules/bwie-system/src/main/resources/bootstrap.yml b/bwie-modules/bwie-system/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..2f63bd8 --- /dev/null +++ b/bwie-modules/bwie-system/src/main/resources/bootstrap.yml @@ -0,0 +1,30 @@ +# Tomcat +server: + port: 9002 +# Spring +spring: + main: + allow-circular-references: true # 允许循环依赖 + jackson: # json 序列化 和 返序列化 转换 + date-format: yyyy-MM-dd HH:mm:ss + time-zone: GMT+8 + application: + # 应用名称 + name: bwie-system + profiles: + # 环境配置 + active: dev + cloud: + nacos: + discovery: + # 服务注册地址 + server-addr: 123.249.113.136:8848 + config: + # 配置中心地址 + server-addr: 123.249.113.136:8848 + namespace: a9b66e92-e507-47ba-9674-6f939f793aca + # 配置文件格式 + file-extension: yml + # 共享配置 + shared-configs: + - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} diff --git a/bwie-modules/bwie-system/src/main/resources/mapper/SysUserMapper.xml b/bwie-modules/bwie-system/src/main/resources/mapper/SysUserMapper.xml new file mode 100644 index 0000000..cd142ae --- /dev/null +++ b/bwie-modules/bwie-system/src/main/resources/mapper/SysUserMapper.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/bwie-modules/pom.xml b/bwie-modules/pom.xml new file mode 100644 index 0000000..8bc5a20 --- /dev/null +++ b/bwie-modules/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + com.bwie + bwie-1016 + 1.0-SNAPSHOT + + + bwie-modules + pom + + bwie-system + bwie-goods + bwie-rabbitmq + bwie-sms + bwie-es + bwie-kafka + + + + 8 + 8 + UTF-8 + + + diff --git a/bwie-modules/src/main/java/com/bwie/Main.java b/bwie-modules/src/main/java/com/bwie/Main.java new file mode 100644 index 0000000..97394bf --- /dev/null +++ b/bwie-modules/src/main/java/com/bwie/Main.java @@ -0,0 +1,13 @@ +package com.bwie; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/16 + */ +public class Main { + public static void main(String[] args) { + System.out.println("Hello world!"); + } +} diff --git a/bwie-rabbit/pom.xml b/bwie-rabbit/pom.xml new file mode 100644 index 0000000..9579589 --- /dev/null +++ b/bwie-rabbit/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + com.bwie + bwie-1016 + 1.0-SNAPSHOT + + + bwie-rabbit + + + + com.bwie + bwie-common + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-amqp + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + + diff --git a/bwie-rabbit/src/main/java/com/bwie/rabbit/RabbitApplication.java b/bwie-rabbit/src/main/java/com/bwie/rabbit/RabbitApplication.java new file mode 100644 index 0000000..cc1e02a --- /dev/null +++ b/bwie-rabbit/src/main/java/com/bwie/rabbit/RabbitApplication.java @@ -0,0 +1,19 @@ +package com.bwie.rabbit; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/23 + */ +@SpringBootApplication +public class RabbitApplication { + + public static void main(String[] args) { + SpringApplication.run(RabbitApplication.class); + } + +} diff --git a/bwie-rabbit/src/main/java/com/bwie/rabbit/config/RabbitAdminConfig.java b/bwie-rabbit/src/main/java/com/bwie/rabbit/config/RabbitAdminConfig.java new file mode 100644 index 0000000..d3548b4 --- /dev/null +++ b/bwie-rabbit/src/main/java/com/bwie/rabbit/config/RabbitAdminConfig.java @@ -0,0 +1,44 @@ +package com.bwie.rabbit.config; + +import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; +import org.springframework.amqp.rabbit.connection.ConnectionFactory; +import org.springframework.amqp.rabbit.core.RabbitAdmin; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * RabbitAdmin的配置 构建 RabbitAdmin + */ +@Configuration +public class RabbitAdminConfig { + + @Value("${spring.rabbitmq.host}") + private String host; + + @Value("${spring.rabbitmq.username}") + private String username; + + @Value("${spring.rabbitmq.password}") + private String password; + + @Value("${spring.rabbitmq.virtualhost}") + private String virtualhost; + + @Bean + public ConnectionFactory connectionFactory() { + CachingConnectionFactory connectionFactory = new CachingConnectionFactory(); + connectionFactory.setAddresses(host); + connectionFactory.setUsername(username); + connectionFactory.setPassword(password); + connectionFactory.setVirtualHost(virtualhost); + return connectionFactory; + } + + @Bean + public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) { + RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory); + rabbitAdmin.setAutoStartup(true); + return rabbitAdmin; + } +} diff --git a/bwie-rabbit/src/main/java/com/bwie/rabbit/consumer/DelayedQueueConsumer.java b/bwie-rabbit/src/main/java/com/bwie/rabbit/consumer/DelayedQueueConsumer.java new file mode 100644 index 0000000..b46b92e --- /dev/null +++ b/bwie-rabbit/src/main/java/com/bwie/rabbit/consumer/DelayedQueueConsumer.java @@ -0,0 +1,23 @@ +package com.bwie.rabbit.consumer; + +import lombok.extern.log4j.Log4j2; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/23 + */ +@Component +@Log4j2 +public class DelayedQueueConsumer { + + @RabbitListener(queuesToDeclare = { @Queue(name = "delayed_queue")}) + public void delayedQueueConsumer(String message) { + log.info("消费者接到消息,消息内容:{}", message); + } + +} diff --git a/bwie-rabbit/src/main/java/com/bwie/rabbit/consumer/TTLQueueConsumer.java b/bwie-rabbit/src/main/java/com/bwie/rabbit/consumer/TTLQueueConsumer.java new file mode 100644 index 0000000..240000c --- /dev/null +++ b/bwie-rabbit/src/main/java/com/bwie/rabbit/consumer/TTLQueueConsumer.java @@ -0,0 +1,23 @@ +package com.bwie.rabbit.consumer; + +import lombok.extern.log4j.Log4j2; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/23 + */ +//@Component +@Log4j2 +public class TTLQueueConsumer { + + @RabbitListener(queuesToDeclare = {@Queue(name = "ttl_queue")}) + public void ttlQueueConsumer(String message) { + log.info("消费者接到消息,消息内容:{}", message); + } + +} diff --git a/bwie-rabbit/src/main/java/com/bwie/rabbit/controller/HelloController.java b/bwie-rabbit/src/main/java/com/bwie/rabbit/controller/HelloController.java new file mode 100644 index 0000000..02d070f --- /dev/null +++ b/bwie-rabbit/src/main/java/com/bwie/rabbit/controller/HelloController.java @@ -0,0 +1,51 @@ +package com.bwie.rabbit.controller; + +import com.bwie.rabbit.utils.DLXQueue; +import com.bwie.rabbit.utils.DelayedQueue; +import com.bwie.rabbit.utils.TtlQueue; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @ClassName: + * @Description: + * @Author: zhuwenqiang + * @Date: 2023/10/23 + */ +@RestController +@RequestMapping("rabbit") +public class HelloController { + + @Autowired + private DelayedQueue delayedQueue; + + @Autowired + private TtlQueue ttlQueue; + + @Autowired + private DLXQueue dlxQueue; + + @GetMapping("send/delayed/message") + public String sendDelayedMessage() { + // 发送延迟消息 + delayedQueue.sendDelayedQueue("delayed_queue", "hello delayed message", 5000); + return "ok"; + } + + @GetMapping("send/ttl/message") + public String sendTtlMessage() { + // 发送ttl + ttlQueue.sendTtlQueue("ttl_queue", "hello ttl", 5000); + return "ok"; + } + + @GetMapping("send/dlx/message") + public String sendDlxMessage() { + // 发送 ttl -> dlx + dlxQueue.sendDLXQueue("normal_queue", "dead_queue", "hell dlx", 5000); + return "ok"; + } + +} diff --git a/bwie-rabbit/src/main/java/com/bwie/rabbit/utils/DLXQueue.java b/bwie-rabbit/src/main/java/com/bwie/rabbit/utils/DLXQueue.java new file mode 100644 index 0000000..3657aed --- /dev/null +++ b/bwie-rabbit/src/main/java/com/bwie/rabbit/utils/DLXQueue.java @@ -0,0 +1,81 @@ +package com.bwie.rabbit.utils; + +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.rabbit.core.RabbitAdmin; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Map; + +@Component +public class DLXQueue { + // routingKey + private static final String DEAD_ROUTING_KEY = "dead.routingkey"; + private static final String ROUTING_KEY = "routingkey"; + private static final String DEAD_EXCHANGE = "dead.exchange"; + private static final String EXCHANGE = "common.exchange"; + @Autowired + RabbitTemplate rabbitTemplate; + @Resource + RabbitAdmin rabbitAdmin; + + /** + * 发送死信队列,过期后进入死信交换机,进入死信队列 + * + * @param queueName 队列名称 + * @param deadQueueName 死信队列名称 + * @param params 消息内容 + * @param expiration 过期时间 毫秒 + */ + public void sendDLXQueue(String queueName, String deadQueueName, Object params, Integer expiration) { + /** + * ----------------------------------先创建一个ttl队列------------------------------------------- + */ + Map map = new HashMap<>(); + // 队列设置存活时间,单位ms, 必须是整形数据。 + map.put("x-message-ttl", expiration); + // 设置死信交换机 + map.put("x-dead-letter-exchange", DEAD_EXCHANGE); + // 设置死信交换器路由 + map.put("x-dead-letter-routing-key", DEAD_ROUTING_KEY); + /*参数1:队列名称 参数2:持久化 参数3:是否排他 参数4:自动删除队列 参数5:队列参数*/ + Queue queue = new Queue(queueName, true, false, false, map); + rabbitAdmin.declareQueue(queue); + + /** + * ---------------------------------创建交换机--------------------------------------------- + */ + DirectExchange directExchange = new DirectExchange(EXCHANGE, true, false); + rabbitAdmin.declareExchange(directExchange); + + /** + * ---------------------------------队列绑定交换机--------------------------------------------- + */ + Binding binding = BindingBuilder.bind(queue).to(directExchange).with(ROUTING_KEY); + rabbitAdmin.declareBinding(binding); + + /** + * ---------------------------------在创建一个死信交换机和队列,接收死信队列--------------------------------------------- + */ + DirectExchange deadExchange = new DirectExchange(DEAD_EXCHANGE, true, false); + rabbitAdmin.declareExchange(deadExchange); + + Queue deadQueue = new Queue(deadQueueName, true, false, false); + rabbitAdmin.declareQueue(deadQueue); + + /** + * ---------------------------------队列绑定死信交换机--------------------------------------------- + */ + Binding deadbinding = BindingBuilder.bind(deadQueue).to(deadExchange).with(DEAD_ROUTING_KEY); + rabbitAdmin.declareBinding(deadbinding); + + // 发送消息 ttl + rabbitTemplate.convertAndSend(EXCHANGE, ROUTING_KEY, params); + } +} diff --git a/bwie-rabbit/src/main/java/com/bwie/rabbit/utils/DelayedQueue.java b/bwie-rabbit/src/main/java/com/bwie/rabbit/utils/DelayedQueue.java new file mode 100644 index 0000000..dc041f3 --- /dev/null +++ b/bwie-rabbit/src/main/java/com/bwie/rabbit/utils/DelayedQueue.java @@ -0,0 +1,85 @@ +package com.bwie.rabbit.utils; + +import org.springframework.amqp.AmqpException; +import org.springframework.amqp.core.*; +import org.springframework.amqp.rabbit.core.RabbitAdmin; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 发送延迟队列 + */ +@Component +public class DelayedQueue { + /** + * routingKey + */ + private static final String DELAYED_ROUTING_KEY = "delayed.routingkey"; + + /** + * 延迟队列交换机名称 + */ + private static final String DELAYED_EXCHANGE = "delayed.exchange"; + + @Autowired + RabbitTemplate rabbitTemplate; + + @Resource + RabbitAdmin rabbitAdmin; + + /** + * 发送延迟队列 + * + * @param queueName 队列名称 + * @param params 消息内容 + * @param delayedTime 延迟时间 毫秒 + */ + public void sendDelayedQueue(String queueName, Object params, Integer delayedTime) { + // 先创建一个队列 + Queue queue = new Queue(queueName, true); + rabbitAdmin.declareQueue(queue); + + // 创建延迟队列交换机 + CustomExchange customExchange = createCustomExchange(); + rabbitAdmin.declareExchange(customExchange); + + // 将队列和交换机绑定 + Binding binding = BindingBuilder.bind(queue).to(customExchange).with(DELAYED_ROUTING_KEY).noargs(); + rabbitAdmin.declareBinding(binding); + + // 发送延迟消息 + rabbitTemplate.convertAndSend(DELAYED_EXCHANGE, DELAYED_ROUTING_KEY, params, message -> { + // 设置延迟时间 + message.getMessageProperties().setDelay(delayedTime); + return message; + }); + } + + /** + * 创建自定义交换机 + * + * @return + */ + public CustomExchange createCustomExchange() { + /** + * 参数说明: + * 1.交换机的名称 + * 2.交换机的类型 + * 3.是否需要持久化 + * 4.是否自动删除 + * 5.其它参数 + */ + Map arguments = new HashMap<>(); + arguments.put("x-delayed-type", "direct"); + return new CustomExchange(DELAYED_EXCHANGE, "x-delayed-message", true, false, arguments); + } + +} + diff --git a/bwie-rabbit/src/main/java/com/bwie/rabbit/utils/TtlQueue.java b/bwie-rabbit/src/main/java/com/bwie/rabbit/utils/TtlQueue.java new file mode 100644 index 0000000..3637ca3 --- /dev/null +++ b/bwie-rabbit/src/main/java/com/bwie/rabbit/utils/TtlQueue.java @@ -0,0 +1,70 @@ +package com.bwie.rabbit.utils; + +import org.springframework.amqp.core.*; +import org.springframework.amqp.rabbit.core.RabbitAdmin; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Map; + +/** + * 发送TTL队列 + */ +@Component +public class TtlQueue { + /** + * routingKey + */ + private static final String TTL_KEY = "ttl.routingkey"; + + /** + * TTL交换机名称 + */ + private static final String TTL_EXCHANGE = "ttl.exchange"; + + @Autowired + private RabbitTemplate rabbitTemplate; + + @Resource + private RabbitAdmin rabbitAdmin; + + /** + * 发送TTL队列 + * + * @param queueName 队列名称 + * @param params 消息内容 + * @param expiration 过期时间 毫秒 + */ + public void sendTtlQueue(String queueName, Object params, Integer expiration) { + /** + * ----------------------------------先创建一个ttl队列-------------------------------------------- + */ + Map map = new HashMap<>(); + // 队列设置存活时间,单位ms,必须是整形数据。 + map.put("x-message-ttl", expiration); + /*参数1:队列名称 参数2:持久化 参数3:是否排他 参数4:自动删除队列 参数5:队列参数*/ + Queue queue = new Queue(queueName, true, false, false, map); + rabbitAdmin.declareQueue(queue); + + /** + * ---------------------------------创建交换机--------------------------------------------- + */ + DirectExchange directExchange = new DirectExchange(TTL_EXCHANGE, true, false); + rabbitAdmin.declareExchange(directExchange); + + /** + * ---------------------------------队列绑定交换机--------------------------------------------- + */ + Binding binding = BindingBuilder.bind(queue).to(directExchange).with(TTL_KEY); + rabbitAdmin.declareBinding(binding); + + /** + * ---------------------------------发送消息--------------------------------------------- + */ + rabbitTemplate.convertAndSend(TTL_EXCHANGE, TTL_KEY, params); + } +} + diff --git a/bwie-rabbit/src/main/resources/bootstrap.yml b/bwie-rabbit/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..5cce278 --- /dev/null +++ b/bwie-rabbit/src/main/resources/bootstrap.yml @@ -0,0 +1,38 @@ +# Tomcat +server: + port: 9005 +# Spring +spring: + rabbitmq: + host: 123.249.113.136 + port: 5672 + username: guest + password: guest + virtual-host: / + listener: + simple: + prefetch: 1 # 每次取出来一条消息,消费完毕之后取下一条消费 + main: + allow-circular-references: true # 允许循环依赖 + jackson: # json 序列化 和 返序列化 转换 + date-format: yyyy-MM-dd HH:mm:ss + time-zone: GMT+8 + application: + # 应用名称 + name: bwie-rabbitmq + profiles: + # 环境配置 + active: dev + cloud: + nacos: + discovery: + # 服务注册地址 + server-addr: 123.249.113.136:8848 + config: + # 配置中心地址 + server-addr: 123.249.113.136:8848 + # 配置文件格式 + file-extension: yml + # 共享配置 + shared-configs: + - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}