master
commit
1fb0125cbc
|
@ -0,0 +1,35 @@
|
|||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**/target/
|
||||
!**/src/test/**/target/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### Eclipse ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Mac OS ###
|
||||
.DS_Store
|
|
@ -0,0 +1,32 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.bwie</groupId>
|
||||
<artifactId>last-month</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>bwie-auth</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<!-- 项目公共 依赖 -->
|
||||
<dependency>
|
||||
<groupId>com.bwie</groupId>
|
||||
<artifactId>bwie-common</artifactId>
|
||||
</dependency>
|
||||
<!-- SpringBoot Web-->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-amqp</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,13 @@
|
|||
package com.bwie;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableFeignClients
|
||||
public class AuthApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(AuthApplication.class,args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.bwie.auth.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;
|
||||
|
||||
@Component
|
||||
public class ConfirmCallbackConfig implements RabbitTemplate.ConfirmCallback {
|
||||
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
/**
|
||||
* 当前bean初始化的时候执行
|
||||
*/
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.rabbitTemplate.setConfirmCallback(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认方法
|
||||
* @param correlationData correlation data for the callback.
|
||||
* @param ack true for ack, false for nack
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.bwie.auth.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @Author:chengjing
|
||||
* @Package:com.bwie.auth.config
|
||||
* @Project:zuoye4.9
|
||||
* @name:InitPasswordEncode
|
||||
* @Date:2024/4/10 7:36
|
||||
*/
|
||||
@Component
|
||||
public class InitPasswordEncode {
|
||||
|
||||
@Bean
|
||||
public BCryptPasswordEncoder bCryptPasswordEncoder(){
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.bwie.auth.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
|
||||
*/
|
||||
@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.virtual-host}")
|
||||
private String virtualhost;
|
||||
|
||||
@Bean
|
||||
public ConnectionFactory connectionFactory() {
|
||||
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
|
||||
connectionFactory.setAddresses(host);
|
||||
connectionFactory.setUsername(username);
|
||||
connectionFactory.setPassword(password);
|
||||
connectionFactory.setVirtualHost(virtualhost);
|
||||
// 配置发送确认回调时,次配置必须配置,否则即使在RabbitTemplate配置了ConfirmCallback也不会生效
|
||||
connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
|
||||
connectionFactory.setPublisherReturns(true);
|
||||
return connectionFactory;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* rabbitAdmin
|
||||
* @param connectionFactory
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
|
||||
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
|
||||
rabbitAdmin.setAutoStartup(true);
|
||||
return rabbitAdmin;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.bwie.auth.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 {
|
||||
// 消息转换配置
|
||||
@Bean
|
||||
public MessageConverter jsonMessageConverter(){
|
||||
return new Jackson2JsonMessageConverter();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.bwie.auth.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;
|
||||
|
||||
@Component
|
||||
public class ReturnsCallbackConfig implements RabbitTemplate.ReturnsCallback {
|
||||
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
/**
|
||||
* 当前bean初始化的时候执行
|
||||
*/
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.rabbitTemplate.setReturnsCallback(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息发送达到 queue 失败执行
|
||||
*
|
||||
* @param returnedMessage the returned message and metadata.
|
||||
*/
|
||||
@Override
|
||||
public void returnedMessage(ReturnedMessage returnedMessage) {
|
||||
System.out.println("消息" + returnedMessage.getMessage().toString() +
|
||||
"被交换机" + returnedMessage.getExchange() + "回退!"
|
||||
+ "退回原因为:" + returnedMessage.getReplyText());
|
||||
// TODO 回退了所有的信息,可做补偿机制
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.bwie.auth.controller;
|
||||
|
||||
import com.bwie.auth.service.AuthService;
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.domain.response.JwtResponse;
|
||||
import com.bwie.common.result.Result;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth")
|
||||
public class AuthController {
|
||||
|
||||
@Autowired
|
||||
private AuthService authService;
|
||||
|
||||
/**
|
||||
* 发送验证码
|
||||
* @param userPhone
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/getCode/{userPhone}")
|
||||
public Result<String> getCode(@PathVariable String userPhone){
|
||||
authService.getCode(userPhone);
|
||||
return Result.success(null,"验证码发送成功");
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录
|
||||
* @param user
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/login")
|
||||
public Result<JwtResponse> login(@RequestBody User user){
|
||||
return Result.success(authService.login(user),"登陆成功");
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录人信息
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/getInfo")
|
||||
public Result<User> getInfo(){
|
||||
return Result.success(authService.getInfo(),"查询成功");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.bwie.auth.feign;
|
||||
|
||||
import com.bwie.auth.feign.factory.UserFactory;
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.result.Result;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
@FeignClient(value = "bwie-user",fallbackFactory = UserFactory.class )
|
||||
public interface UserFeign {
|
||||
|
||||
@PostMapping("/user/selectUserPhone")
|
||||
public Result<User> selectUserPhone(@RequestParam String userPhone);
|
||||
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.bwie.auth.feign.factory;
|
||||
|
||||
import com.bwie.auth.feign.UserFeign;
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.result.Result;
|
||||
import org.springframework.cloud.openfeign.FallbackFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class UserFactory implements FallbackFactory<UserFeign> {
|
||||
@Override
|
||||
public UserFeign create(Throwable cause) {
|
||||
return new UserFeign() {
|
||||
@Override
|
||||
public Result<User> selectUserPhone(String userPhone) {
|
||||
return Result.error("网络走丢了");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.bwie.auth.service;
|
||||
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.domain.response.JwtResponse;
|
||||
|
||||
public interface AuthService {
|
||||
void getCode(String userPhone);
|
||||
|
||||
JwtResponse login(User user);
|
||||
|
||||
User getInfo();
|
||||
}
|
|
@ -0,0 +1,92 @@
|
|||
package com.bwie.auth.service.impl;
|
||||
|
||||
import cn.hutool.jwt.JWT;
|
||||
import cn.hutool.jwt.JWTUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.bwie.auth.feign.UserFeign;
|
||||
import com.bwie.auth.service.AuthService;
|
||||
import com.bwie.common.constants.JwtConstants;
|
||||
import com.bwie.common.constants.TokenConstants;
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.domain.response.JwtResponse;
|
||||
import com.bwie.common.utils.JwtUtils;
|
||||
import com.bwie.common.utils.StringUtils;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.HashMap;
|
||||
import java.util.Objects;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@Log4j2
|
||||
public class AuthServiceImpl implements AuthService {
|
||||
|
||||
@Autowired
|
||||
private UserFeign userFeign;
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Override
|
||||
public void getCode(String userPhone) {
|
||||
if(StringUtils.isBlank(userPhone)){
|
||||
throw new RuntimeException("手机号不能为空");
|
||||
}
|
||||
User user = userFeign.selectUserPhone(userPhone).getData();
|
||||
if(null == user){
|
||||
throw new RuntimeException("账号不存在");
|
||||
}
|
||||
int nextInfo = new Random().nextInt(9000) + 1000;
|
||||
String code = String.valueOf(nextInfo);
|
||||
redisTemplate.opsForValue().set(userPhone,code,5, TimeUnit.MINUTES);
|
||||
log.info("验证码为:{}",code);
|
||||
}
|
||||
|
||||
@Override
|
||||
public JwtResponse login(User user) {
|
||||
if(StringUtils.isAllBlank(user.getUserPhone(),user.getCode())){
|
||||
throw new RuntimeException("请输入手机号和验证码");
|
||||
}
|
||||
User userLogin = userFeign.selectUserPhone(user.getUserPhone()).getData();
|
||||
if(null == userLogin){
|
||||
throw new RuntimeException("无此账号则需要先录入到系统");
|
||||
}
|
||||
String code = redisTemplate.opsForValue().get(userLogin.getUserPhone());
|
||||
if(code == null){
|
||||
throw new RuntimeException("请重新发送验证码");
|
||||
}
|
||||
if(!code.equals(user.getCode())){
|
||||
throw new RuntimeException("验证码输入错误");
|
||||
}
|
||||
|
||||
String userKey = UUID.randomUUID().toString().replaceAll("-", "");
|
||||
HashMap<String, Object> stringHashMap = new HashMap<>();
|
||||
stringHashMap.put(JwtConstants.USER_KEY,userKey);
|
||||
String token = JwtUtils.createToken(stringHashMap);
|
||||
|
||||
redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSON.toJSONString(userLogin),30,TimeUnit.MINUTES);
|
||||
|
||||
JwtResponse jwtResponse = new JwtResponse();
|
||||
jwtResponse.setToken(token);
|
||||
jwtResponse.setExistTime("30MIN");
|
||||
return jwtResponse;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public User getInfo() {
|
||||
String token = request.getHeader(TokenConstants.TOKEN);
|
||||
String userKey = JwtUtils.getUserKey(token);
|
||||
String user = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
|
||||
return JSON.parseObject(user,User.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
# Tomcat
|
||||
server:
|
||||
port: 9004
|
||||
# Spring
|
||||
spring:
|
||||
rabbitmq:
|
||||
host: 47.102.213.213
|
||||
port: 5672
|
||||
username: guest
|
||||
password: guest
|
||||
virtual-host: /
|
||||
listener:
|
||||
simple:
|
||||
prefetch: 1 # 默认每次取出一条消息消费, 消费完成取下一条
|
||||
acknowledge-mode: manual # 设置消费端手动ack确认
|
||||
retry:
|
||||
enabled: true # 是否支持重试
|
||||
publisher-confirm-type: correlated #确认消息已发送到交换机(Exchange)
|
||||
publisher-returns: true #确认消息已发送到队列(Queue)
|
||||
main:
|
||||
allow-circular-references: true
|
||||
jackson:
|
||||
date-format: yyyy-MM-dd HH:mm:ss
|
||||
time-zone: GMT+8
|
||||
application:
|
||||
# 应用名称
|
||||
name: bwie-auth
|
||||
profiles:
|
||||
# 环境配置
|
||||
active: dev
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
# 服务注册地址
|
||||
server-addr: 47.102.213.213:8848
|
||||
namespace: csh
|
||||
config:
|
||||
# 配置中心地址
|
||||
server-addr: 47.102.213.213:8848
|
||||
# 配置文件格式
|
||||
file-extension: yml
|
||||
# 共享配置
|
||||
shared-configs:
|
||||
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
|
||||
namespace: csh
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.bwie</groupId>
|
||||
<artifactId>last-month</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>bwie-common</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<!-- bootstrap 启动器 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-bootstrap</artifactId>
|
||||
</dependency>
|
||||
<!-- SpringCloud Alibaba Nacos -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
<!-- SpringCloud Alibaba Nacos Config -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
<!-- SpringCloud Alibaba Sentinel -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
||||
</dependency>
|
||||
<!-- 负载均衡-->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
|
||||
</dependency>
|
||||
<!-- SpringCloud Openfeign -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||
</dependency>
|
||||
<!-- JWT -->
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt</artifactId>
|
||||
<version>0.9.1</version>
|
||||
</dependency>
|
||||
<!-- Alibaba Fastjson -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>1.2.80</version>
|
||||
</dependency>
|
||||
<!-- SpringBoot Boot Redis -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
<!-- Hibernate Validator -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<!-- Apache Lang3 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
</dependency>
|
||||
<!-- lombok依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</dependency>
|
||||
<!-- hutool -->
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-all</artifactId>
|
||||
<version>5.8.3</version>
|
||||
</dependency>
|
||||
<!-- 阿里大鱼 -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>dysmsapi20170525</artifactId>
|
||||
<version>2.0.1</version>
|
||||
</dependency>
|
||||
<!-- oss 图片上传 -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun.oss</groupId>
|
||||
<artifactId>aliyun-sdk-oss</artifactId>
|
||||
<version>3.12.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- <!–mq 依赖–>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-amqp</artifactId>
|
||||
</dependency>-->
|
||||
|
||||
<!--fastDfs文件上传-->
|
||||
<dependency>
|
||||
<groupId>com.github.tobato</groupId>
|
||||
<artifactId>fastdfs-client</artifactId>
|
||||
<version>1.26.5</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-amqp</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,40 @@
|
|||
package com.bwie.common.config;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
|
||||
RedisTemplate<String, Object> template = new RedisTemplate<>();
|
||||
template.setConnectionFactory(factory);
|
||||
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new
|
||||
Jackson2JsonRedisSerializer(Object.class);
|
||||
ObjectMapper om = new ObjectMapper();
|
||||
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
|
||||
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
|
||||
jackson2JsonRedisSerializer.setObjectMapper(om);
|
||||
|
||||
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
|
||||
// key采用String的序列化方式
|
||||
template.setKeySerializer(stringRedisSerializer);
|
||||
// hash的key也采用String的序列化方式
|
||||
template.setHashKeySerializer(stringRedisSerializer);
|
||||
// value序列化方式采用jackson
|
||||
template.setValueSerializer(jackson2JsonRedisSerializer);
|
||||
// hash的value序列化方式采用jackson
|
||||
template.setHashValueSerializer(jackson2JsonRedisSerializer);
|
||||
template.afterPropertiesSet();
|
||||
|
||||
return template;
|
||||
}
|
||||
}
|
|
@ -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 = "操作异常";
|
||||
}
|
|
@ -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";
|
||||
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.bwie.common.constants;
|
||||
|
||||
public class RabbitMQConstants {
|
||||
public static final String SEND_SMS_QUEUE = "send_sms_queue";
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.bwie.common.constants;
|
||||
|
||||
/**
|
||||
* @author DongZl
|
||||
* @description: 令牌常量
|
||||
*/
|
||||
public class TokenConstants {
|
||||
/**
|
||||
* 缓存有效期,默认720(分钟)
|
||||
*/
|
||||
public final static long EXPIRATION = 720;
|
||||
/**
|
||||
* 缓存刷新时间,默认120(分钟)
|
||||
*/
|
||||
public final static long REFRESH_TIME = 120;
|
||||
/**
|
||||
* 权限缓存前缀
|
||||
*/
|
||||
public final static String LOGIN_TOKEN_KEY = "login_tokens:";
|
||||
/**
|
||||
* token标识
|
||||
*/
|
||||
public static final String TOKEN = "token";
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.bwie.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
|
||||
/**
|
||||
* 券码 信息表
|
||||
*/
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Builder
|
||||
public class Coupon {
|
||||
|
||||
|
||||
/**
|
||||
* 劵码Id
|
||||
*/
|
||||
private String couponId;
|
||||
|
||||
/**
|
||||
* 劵码名称
|
||||
*/
|
||||
private String couponName;
|
||||
|
||||
/**
|
||||
* 劵码分类
|
||||
*/
|
||||
private String sortId;
|
||||
|
||||
/**
|
||||
* 劵码类型
|
||||
*/
|
||||
private String typeId;
|
||||
|
||||
/**
|
||||
* 劵码数量
|
||||
*/
|
||||
private String couponNum;
|
||||
|
||||
/**
|
||||
* 单张劵码价格
|
||||
*/
|
||||
private BigDecimal couponPrice;
|
||||
|
||||
/**
|
||||
* 劵码状态
|
||||
*/
|
||||
private String couponStatus;
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.bwie.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 中间表
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class Middle {
|
||||
|
||||
/**
|
||||
* 中间表id
|
||||
*/
|
||||
private Integer middleId;
|
||||
|
||||
/**
|
||||
* 卖券记录表id
|
||||
*/
|
||||
private Integer orderId;
|
||||
|
||||
/**
|
||||
* 购买记录表id
|
||||
*/
|
||||
private Integer purchaseId;
|
||||
|
||||
/**
|
||||
* 券码表id
|
||||
*/
|
||||
private Integer couponId;
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.bwie.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 售卖记录表
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Builder
|
||||
public class Order {
|
||||
|
||||
/**
|
||||
* 出售id
|
||||
*/
|
||||
private Integer orderId;
|
||||
|
||||
/**
|
||||
* 出售券码id
|
||||
*/
|
||||
private Integer couponId;
|
||||
|
||||
/**
|
||||
* 出售时间
|
||||
*/
|
||||
private String transferTime;
|
||||
|
||||
/**
|
||||
* 截止时间
|
||||
*/
|
||||
private String endTime;
|
||||
|
||||
/**
|
||||
* 出售状态
|
||||
*/
|
||||
private Integer orderStatus;
|
||||
|
||||
/**
|
||||
* 出售人id
|
||||
*/
|
||||
private Integer userId;
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.bwie.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 购买记录表
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class Purchase {
|
||||
/**
|
||||
* 购买记录id
|
||||
*/
|
||||
private Integer purchaseId;
|
||||
|
||||
/**
|
||||
* 券码信息id
|
||||
*/
|
||||
private Integer couponId;
|
||||
|
||||
/**
|
||||
* 购买时间
|
||||
*/
|
||||
private String createTime;
|
||||
|
||||
/**
|
||||
* 花费价格
|
||||
*/
|
||||
private BigDecimal purchasePrice;
|
||||
|
||||
/**
|
||||
* 购买状态
|
||||
*/
|
||||
private Integer purchaseStates;
|
||||
|
||||
/**
|
||||
* 购买人id
|
||||
*/
|
||||
private Integer userId;
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.bwie.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 个人库存表
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class Stash {
|
||||
|
||||
/**
|
||||
* 库存id
|
||||
*/
|
||||
private Integer stashId;
|
||||
|
||||
/**
|
||||
* 库存券码id
|
||||
*/
|
||||
private Integer couponId;
|
||||
|
||||
/**
|
||||
* 库存人
|
||||
*/
|
||||
private Integer userId;
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.bwie.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 用户表
|
||||
*/
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Builder
|
||||
public class User {
|
||||
|
||||
/**
|
||||
* 用户id
|
||||
*/
|
||||
private Integer userId;
|
||||
|
||||
/**
|
||||
* 用户手机号
|
||||
*/
|
||||
private String userPhone;
|
||||
|
||||
/**
|
||||
* 用户密码
|
||||
*/
|
||||
private String userPwd;
|
||||
|
||||
/**
|
||||
* 用户余额
|
||||
*/
|
||||
private BigDecimal userPrice;
|
||||
|
||||
/**
|
||||
* 登录验证码
|
||||
*/
|
||||
private String code;
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.bwie.common.domain.request;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Builder
|
||||
public class EsReq {
|
||||
|
||||
private Integer sortId;
|
||||
private Integer typeId;
|
||||
private String couponName;
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.bwie.common.domain.request;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class StashReq {
|
||||
|
||||
private Integer sortId;
|
||||
private Integer typeId;
|
||||
private Integer userId;
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.bwie.common.domain.response;
|
||||
|
||||
import com.bwie.common.domain.Coupon;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
public class CouponResp extends Coupon {
|
||||
|
||||
/**
|
||||
* 类型名称
|
||||
*/
|
||||
private String typeName;
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.bwie.common.domain.response;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class JwtResponse {
|
||||
private String token;
|
||||
private String existTime;
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.bwie.common.domain.response;
|
||||
|
||||
import com.bwie.common.domain.Purchase;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
public class PurchaseResp extends Purchase {
|
||||
|
||||
private String couponName;
|
||||
private String sortName;
|
||||
private String typeName;
|
||||
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
package com.bwie.common.domain.response;
|
||||
|
||||
import com.bwie.common.domain.Stash;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
public class StashResp extends Stash {
|
||||
|
||||
|
||||
/**
|
||||
* 劵码名称
|
||||
*/
|
||||
private String couponName;
|
||||
|
||||
/**
|
||||
* 劵码分类id
|
||||
*/
|
||||
private Integer sortId;
|
||||
|
||||
/**
|
||||
* 劵码分类名
|
||||
*/
|
||||
private String sortName;
|
||||
|
||||
/**
|
||||
* 劵码类型id
|
||||
*/
|
||||
private Integer typeId;
|
||||
|
||||
/**
|
||||
* 劵码类型名字
|
||||
*/
|
||||
private String typeName;
|
||||
|
||||
/**
|
||||
* 单张劵码价格
|
||||
*/
|
||||
private BigDecimal couponPrice;
|
||||
|
||||
/**
|
||||
* 券码状态
|
||||
*/
|
||||
private Integer couponStatus;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.bwie.common.handler;
|
||||
|
||||
import com.bwie.common.result.Result;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
@RestControllerAdvice
|
||||
@Log4j2
|
||||
public class Exception {
|
||||
|
||||
@ExceptionHandler(value = RuntimeException.class)
|
||||
public Result<String> handle(RuntimeException runtimeException){
|
||||
StackTraceElement stackTraceElement = runtimeException.getStackTrace()[0];
|
||||
String methodName = stackTraceElement.getMethodName();
|
||||
int lineNumber = stackTraceElement.getLineNumber();
|
||||
String fileName = stackTraceElement.getFileName();
|
||||
String className = stackTraceElement.getClassName();
|
||||
log.info("报错的方法是==>{}",methodName);
|
||||
log.info("报错的行数是==>{}",lineNumber);
|
||||
log.info("报错的文件名 是==>{}",fileName);
|
||||
log.info("报错的类名是==>{}",className);
|
||||
return Result.error("操作失败!~",runtimeException.getMessage());
|
||||
}
|
||||
|
||||
}
|
|
@ -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<T> implements Serializable {
|
||||
/**
|
||||
* 总条数
|
||||
*/
|
||||
private long total;
|
||||
/**
|
||||
* 结果集合
|
||||
*/
|
||||
private List<T> list;
|
||||
public PageResult() {
|
||||
}
|
||||
public PageResult(long total, List<T> list) {
|
||||
this.total = total;
|
||||
this.list = list;
|
||||
}
|
||||
public static <T> PageResult<T> toPageResult(long total, List<T> list){
|
||||
return new PageResult(total , list);
|
||||
}
|
||||
public static <T> Result<PageResult<T>> toResult(long total, List<T> list){
|
||||
return Result.success(PageResult.toPageResult(total,list));
|
||||
}
|
||||
}
|
|
@ -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<T> 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 <T> Result<T> success() {
|
||||
return restResult(null, SUCCESS, Constants.SUCCESS_MSG);
|
||||
}
|
||||
|
||||
public static <T> Result<T> success(T data) {
|
||||
return restResult(data, SUCCESS, Constants.SUCCESS_MSG);
|
||||
}
|
||||
|
||||
public static <T> Result<T> success(T data, String msg) {
|
||||
return restResult(data, SUCCESS, msg);
|
||||
}
|
||||
|
||||
public static <T> Result<T> error() {
|
||||
return restResult(null, FAIL, Constants.ERROR_MSG);
|
||||
}
|
||||
|
||||
public static <T> Result<T> error(String msg) {
|
||||
return restResult(null, FAIL, msg);
|
||||
}
|
||||
|
||||
public static <T> Result<T> error(T data) {
|
||||
return restResult(data, FAIL, Constants.ERROR_MSG);
|
||||
}
|
||||
|
||||
public static <T> Result<T> error(T data, String msg) {
|
||||
return restResult(data, FAIL, msg);
|
||||
}
|
||||
|
||||
public static <T> Result<T> error(int code, String msg) {
|
||||
return restResult(null, code, msg);
|
||||
}
|
||||
|
||||
private static <T> Result<T> restResult(T data, int code, String msg) {
|
||||
Result<T> apiResult = new Result<>();
|
||||
apiResult.setCode(code);
|
||||
apiResult.setData(data);
|
||||
apiResult.setMsg(msg);
|
||||
return apiResult;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.bwie.common.utils;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
|
||||
import com.github.tobato.fastdfs.service.FastFileStorageClient;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
|
||||
@Component
|
||||
public class FastUtil {
|
||||
private static final Logger log = LoggerFactory.getLogger(FastUtil.class);
|
||||
|
||||
@Resource
|
||||
private FastFileStorageClient storageClient ;
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
*/
|
||||
public String upload(MultipartFile multipartFile) throws Exception{
|
||||
String originalFilename = multipartFile.getOriginalFilename().
|
||||
substring(multipartFile.getOriginalFilename().
|
||||
lastIndexOf(".") + 1);
|
||||
StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
|
||||
multipartFile.getInputStream(),
|
||||
multipartFile.getSize(),originalFilename , null);
|
||||
return storePath.getFullPath();
|
||||
}
|
||||
/**
|
||||
* 删除文件
|
||||
*/
|
||||
public String deleteFile(String fileUrl) {
|
||||
if (StringUtils.isEmpty(fileUrl)) {
|
||||
log.info("fileUrl == >>文件路径为空...");
|
||||
return "文件路径不能为空";
|
||||
}
|
||||
try {
|
||||
StorePath storePath = StorePath.parseFromUrl(fileUrl);
|
||||
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
return "删除成功";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,86 @@
|
|||
package com.bwie.common.utils;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* @description: 生成验证码工具类
|
||||
* @Date 2023-5-11 上午 10:09
|
||||
*/
|
||||
public class GenCodeUtils {
|
||||
|
||||
/**
|
||||
* 数字类型
|
||||
*/
|
||||
private static final String NUMBER_STR = "0123456789";
|
||||
/**
|
||||
* 字母类型
|
||||
*/
|
||||
private static final String LETTERS_STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
/**
|
||||
* 短信验证码长度
|
||||
*/
|
||||
private static final Integer SMS_CODE_LENGTH = 4;
|
||||
|
||||
/**
|
||||
* 生成短信四位验证码
|
||||
* @return 验证码
|
||||
*/
|
||||
public static String genLetterStrSms(){
|
||||
return genCode(LETTERS_STR, SMS_CODE_LENGTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成短信四位验证码
|
||||
* @return 验证码
|
||||
*/
|
||||
public static String genNumberCodeSms(){
|
||||
return genCode(NUMBER_STR, SMS_CODE_LENGTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成验证码
|
||||
* @param codeLength 验证码长度
|
||||
* @return 验证码
|
||||
*/
|
||||
public static String genLetterStr(int codeLength){
|
||||
return genCode(LETTERS_STR, codeLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成验证码
|
||||
* @param codeLength 验证码长度
|
||||
* @return 验证码
|
||||
*/
|
||||
public static String genNumberCode( int codeLength){
|
||||
return genCode(NUMBER_STR, codeLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成验证码
|
||||
* @param str 验证码字符串
|
||||
* @param codeLength 验证码长度
|
||||
* @return 验证码
|
||||
*/
|
||||
public static String genCode (String str, int codeLength){
|
||||
//将字符串转换为一个新的字符数组。
|
||||
char[] verificationCodeArray = str.toCharArray();
|
||||
Random random = new Random();
|
||||
//计数器
|
||||
int count = 0;
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
do {
|
||||
//随机生成一个随机数
|
||||
int index = random.nextInt(verificationCodeArray.length);
|
||||
char c = verificationCodeArray[index];
|
||||
//限制四位不重复数字
|
||||
if (stringBuilder.indexOf(String.valueOf(c)) == -1) {
|
||||
stringBuilder.append(c);
|
||||
//计数器加1
|
||||
count++;
|
||||
}
|
||||
//当count等于4时结束,随机生成四位数的验证码
|
||||
} while (count != codeLength);
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,115 @@
|
|||
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工具类
|
||||
*/
|
||||
public class JwtUtils {
|
||||
|
||||
/**
|
||||
* 秘钥
|
||||
*/
|
||||
public static String secret = JwtConstants.SECRET;
|
||||
|
||||
/**
|
||||
* 从数据声明生成令牌
|
||||
*
|
||||
* @param claims 数据声明
|
||||
* @return 令牌
|
||||
*/
|
||||
public static String createToken(Map<String, Object> claims) {
|
||||
String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从令牌中获取数据声明
|
||||
*
|
||||
* @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();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,153 @@
|
|||
package com.bwie.common.utils;
|
||||
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
import com.aliyun.oss.model.GetObjectRequest;
|
||||
import com.aliyun.oss.model.PutObjectRequest;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.*;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Oss服务调用
|
||||
*/
|
||||
@Log4j2
|
||||
public class OssUtil {
|
||||
|
||||
/**
|
||||
* Endpoint 存储对象概述 阿里云主账号AccessKey,accessKeySecret拥有所有API的访问权限 访问路径前缀 存储对象概述
|
||||
*/
|
||||
private static String endPoint = "oss-cn-shanghai.aliyuncs.com";
|
||||
private static String accessKeyId = "LTAI5t6zTKA69UHP5CZGnAqU";
|
||||
private static String accessKeySecret = "p2eeKDgGcdczb8cWxg7blRO54b3T0K";
|
||||
private static String accessPre = "https://csh666.oss-cn-shanghai.aliyuncs.com/";
|
||||
|
||||
/**
|
||||
* bucket名称
|
||||
* @return
|
||||
*/
|
||||
private static String bucketName = "cshnb";
|
||||
|
||||
private static OSS ossClient ;
|
||||
|
||||
static {
|
||||
ossClient = new OSSClientBuilder().build(
|
||||
endPoint,
|
||||
accessKeyId,
|
||||
accessKeySecret);
|
||||
log.info("oss服务连接成功!");
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认路径上传本地文件
|
||||
* @param filePath
|
||||
*/
|
||||
public static String uploadFile(String filePath){
|
||||
return uploadFileForBucket(bucketName,getOssFilePath(filePath) ,filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认路径上传multipartFile文件
|
||||
* @param multipartFile
|
||||
*/
|
||||
public static String uploadMultipartFile(MultipartFile multipartFile) {
|
||||
return uploadMultipartFile(bucketName,getOssFilePath(multipartFile.getOriginalFilename()),multipartFile);
|
||||
}
|
||||
/**
|
||||
* 上传 multipartFile 类型文件
|
||||
* @param bucketName
|
||||
* @param ossPath
|
||||
* @param multipartFile
|
||||
*/
|
||||
public static String uploadMultipartFile(String bucketName , String ossPath , MultipartFile multipartFile){
|
||||
InputStream inputStream = null;
|
||||
try {
|
||||
inputStream = multipartFile.getInputStream();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
uploadFileInputStreamForBucket(bucketName, ossPath, inputStream);
|
||||
return accessPre+ossPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用File上传PutObject上传文件 ** 程序默认使用次方法上传
|
||||
* @param bucketName 实例名称
|
||||
* @param ossPath oss存储路径
|
||||
* @param filePath 本地文件路径
|
||||
*/
|
||||
public static String uploadFileForBucket(String bucketName , String ossPath , String filePath) {
|
||||
// 创建PutObjectRequest对象。
|
||||
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, ossPath, new File(filePath));
|
||||
|
||||
// 上传
|
||||
ossClient.putObject(putObjectRequest);
|
||||
return accessPre+ossPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用文件流上传到指定的bucket实例
|
||||
* @param bucketName 实例名称
|
||||
* @param ossPath oss存储路径
|
||||
* @param filePath 本地文件路径
|
||||
*/
|
||||
public static String uploadFileInputStreamForBucket(String bucketName , String ossPath , String filePath){
|
||||
|
||||
// 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
|
||||
InputStream inputStream = null;
|
||||
try {
|
||||
inputStream = new FileInputStream(filePath);
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
// 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
|
||||
uploadFileInputStreamForBucket(bucketName, ossPath, inputStream);
|
||||
return accessPre+ossPath;
|
||||
}
|
||||
|
||||
public static void uploadFileInputStreamForBucket(String bucketName , String ossPath , InputStream inputStream ){
|
||||
ossClient.putObject(bucketName, ossPath, inputStream);
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载
|
||||
* @param ossFilePath
|
||||
* @param filePath
|
||||
*/
|
||||
public static void downloadFile(String ossFilePath , String filePath ){
|
||||
downloadFileForBucket(bucketName , ossFilePath , filePath);
|
||||
}
|
||||
/**
|
||||
* 下载
|
||||
* @param bucketName 实例名称
|
||||
* @param ossFilePath oss存储路径
|
||||
* @param filePath 本地文件路径
|
||||
*/
|
||||
public static void downloadFileForBucket(String bucketName , String ossFilePath , String filePath ){
|
||||
ossClient.getObject(new GetObjectRequest(bucketName, ossFilePath), new File(filePath));
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static String getOssDefaultPath(){
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
String url =
|
||||
now.getYear()+"/"+
|
||||
now.getMonth()+"/"+
|
||||
now.getDayOfMonth()+"/"+
|
||||
now.getHour()+"/"+
|
||||
now.getMinute()+"/";
|
||||
return url;
|
||||
}
|
||||
|
||||
public static String getOssFilePath(String filePath){
|
||||
String fileSuf = filePath.substring(filePath.indexOf(".") + 1);
|
||||
return getOssDefaultPath() + UUID.randomUUID().toString() + "." + fileSuf;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package com.bwie.common.utils;
|
||||
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @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<String> 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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,96 @@
|
|||
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.dysmsapi20170525.models.SendSmsResponseBody;
|
||||
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 = "LTAI5tDbRqXkC5i3SMrCSDcX";
|
||||
|
||||
private static String accessKeySecret = "XUzMZoHPLsjNLafHsdQnMElBWZATsu";
|
||||
|
||||
/**
|
||||
* 短信访问域名
|
||||
*/
|
||||
private static String endpoint = "dysmsapi.aliyuncs.com";
|
||||
|
||||
/**
|
||||
* 短信签名
|
||||
*/
|
||||
private static String signName = "乐优购";
|
||||
|
||||
/**
|
||||
* 模板编号
|
||||
*/
|
||||
private static String templateCode = "SMS_163851467";
|
||||
|
||||
/**
|
||||
* 实例化短信对象
|
||||
*/
|
||||
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
|
||||
*/
|
||||
public static SendSmsResponseBody sendSms(String tel, Map<String, String> 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 sendSmsResponse.getBody();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
com.bwie.common.handler.Exception
|
|
@ -0,0 +1,40 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.bwie</groupId>
|
||||
<artifactId>last-month</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>bwie-gateway</artifactId>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<!-- 公共模块 -->
|
||||
<dependency>
|
||||
<groupId>com.bwie</groupId>
|
||||
<artifactId>bwie-common</artifactId>
|
||||
</dependency>
|
||||
<!-- 网关依赖 -->
|
||||
<!-- SpringCloud Gateway -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-gateway</artifactId>
|
||||
</dependency>
|
||||
<!-- SpringCloud Alibaba Sentinel Gateway -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
|
||||
</dependency>
|
||||
<!-- 引入阿里巴巴sentinel限流 依赖-->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.csp</groupId>
|
||||
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
|
@ -0,0 +1,11 @@
|
|||
package com.bwie;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class GatewayApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(GatewayApplication.class,args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
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.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Configuration
|
||||
@RefreshScope
|
||||
@ConfigurationProperties(prefix = "ignore")
|
||||
@Data
|
||||
@Log4j2
|
||||
public class IgnoreWhiteConfig {
|
||||
/**
|
||||
* 放行白名单配置,网关不校验此处的白名单
|
||||
*/
|
||||
private List<String> whites = new ArrayList<>();
|
||||
|
||||
public void setWhites(List<String> whites) {
|
||||
log.info("加载网关路径白名单:{}", JSONObject.toJSONString(whites));
|
||||
this.whites = whites;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package com.bwie.gateway.filters;
|
||||
|
||||
import com.bwie.common.constants.TokenConstants;
|
||||
import com.bwie.common.utils.JwtUtils;
|
||||
import com.bwie.common.utils.StringUtils;
|
||||
import com.bwie.gateway.config.IgnoreWhiteConfig;
|
||||
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.Ordered;
|
||||
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.List;
|
||||
|
||||
|
||||
@Component
|
||||
public class AuthFilter implements GlobalFilter, Ordered {
|
||||
|
||||
@Autowired
|
||||
private IgnoreWhiteConfig ignoreWhiteConfig;
|
||||
|
||||
@Autowired
|
||||
private RedisTemplate<String, String> redisTemplate;
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
|
||||
|
||||
List<String> whites = ignoreWhiteConfig.getWhites();
|
||||
|
||||
ServerHttpRequest request = exchange.getRequest();
|
||||
String path = request.getURI().getPath();
|
||||
boolean matches = StringUtils.matches(path, whites);
|
||||
if (matches) {
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
|
||||
String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
|
||||
|
||||
if (StringUtils.isEmpty(token)) {
|
||||
|
||||
return GatewayUtils.errorResponse(exchange, "token不能为空!", HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
try {
|
||||
|
||||
JwtUtils.parseToken(token);
|
||||
} catch (Exception ex) {
|
||||
return GatewayUtils.errorResponse(exchange, "token格式错误!");
|
||||
}
|
||||
|
||||
String userKey = JwtUtils.getUserKey(token);
|
||||
if (!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey)) {
|
||||
return GatewayUtils.errorResponse(exchange, "token过期!");
|
||||
}
|
||||
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return 0;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,95 @@
|
|||
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;
|
||||
|
||||
|
||||
@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<Void> 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<Void> 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));
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
# 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: 47.102.213.213:8848
|
||||
namespace: csh
|
||||
config:
|
||||
# 配置中心地址
|
||||
server-addr: 47.102.213.213:8848
|
||||
# 配置文件格式
|
||||
file-extension: yml
|
||||
# 共享配置
|
||||
shared-configs:
|
||||
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
|
||||
namespace: csh
|
|
@ -0,0 +1,46 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.bwie</groupId>
|
||||
<artifactId>last-month</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<artifactId>bwie-coupon</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<!-- 公共模块 -->
|
||||
<dependency>
|
||||
<groupId>com.bwie</groupId>
|
||||
<artifactId>bwie-common</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<!-- Druid数据库连接池 -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid-spring-boot-starter</artifactId>
|
||||
<version>1.2.8</version>
|
||||
</dependency>
|
||||
<!-- Mybatis 依赖配置 -->
|
||||
<dependency>
|
||||
<groupId>org.mybatis.spring.boot</groupId>
|
||||
<artifactId>mybatis-spring-boot-starter</artifactId>
|
||||
<version>2.2.2</version>
|
||||
</dependency>
|
||||
<!-- Mysql Connector -->
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,15 @@
|
|||
package com.bwie;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableFeignClients
|
||||
@EnableScheduling
|
||||
public class CouponApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CouponApplication.class,args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.bwie.coupon.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.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
|
||||
@Component
|
||||
public class ConfirmCallbackConfig implements RabbitTemplate.ConfirmCallback {
|
||||
|
||||
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
/**
|
||||
* 当前bean初始化的时候执行
|
||||
*/
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.rabbitTemplate.setConfirmCallback(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认方法
|
||||
* @param correlationData correlation data for the callback.
|
||||
* @param ack true for ack, false for nack
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.bwie.coupon.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
|
||||
*/
|
||||
@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.virtual-host}")
|
||||
private String virtualhost;
|
||||
|
||||
@Bean
|
||||
public ConnectionFactory connectionFactory() {
|
||||
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
|
||||
connectionFactory.setAddresses(host);
|
||||
connectionFactory.setUsername(username);
|
||||
connectionFactory.setPassword(password);
|
||||
connectionFactory.setVirtualHost(virtualhost);
|
||||
// 配置发送确认回调时,次配置必须配置,否则即使在RabbitTemplate配置了ConfirmCallback也不会生效
|
||||
connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
|
||||
connectionFactory.setPublisherReturns(true);
|
||||
return connectionFactory;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* rabbitAdmin
|
||||
* @param connectionFactory
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
|
||||
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
|
||||
rabbitAdmin.setAutoStartup(true);
|
||||
return rabbitAdmin;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.bwie.coupon.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 {
|
||||
// 消息转换配置
|
||||
@Bean
|
||||
public MessageConverter jsonMessageConverter(){
|
||||
return new Jackson2JsonMessageConverter();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.bwie.coupon.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;
|
||||
|
||||
|
||||
@Component
|
||||
public class ReturnsCallbackConfig implements RabbitTemplate.ReturnsCallback {
|
||||
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
/**
|
||||
* 当前bean初始化的时候执行
|
||||
*/
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.rabbitTemplate.setReturnsCallback(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息发送达到 queue 失败执行
|
||||
*
|
||||
* @param returnedMessage the returned message and metadata.
|
||||
*/
|
||||
@Override
|
||||
public void returnedMessage(ReturnedMessage returnedMessage) {
|
||||
System.out.println("消息" + returnedMessage.getMessage().toString() +
|
||||
"被交换机" + returnedMessage.getExchange() + "回退!"
|
||||
+ "退回原因为:" + returnedMessage.getReplyText());
|
||||
// TODO 回退了所有的信息,可做补偿机制
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.bwie.coupon.controller;
|
||||
|
||||
import com.bwie.common.domain.Coupon;
|
||||
import com.bwie.common.domain.response.CouponResp;
|
||||
import com.bwie.common.result.Result;
|
||||
import com.bwie.coupon.service.CouponService;
|
||||
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.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/coupon")
|
||||
public class CouponController {
|
||||
|
||||
@Autowired
|
||||
private CouponService couponService;
|
||||
|
||||
/**
|
||||
* 券码列表
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/list")
|
||||
public Result<List<CouponResp>> couponList(){
|
||||
return Result.success(couponService.couponList(),"劵码查询成功");
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.bwie.coupon.controller;
|
||||
|
||||
import com.bwie.common.domain.Order;
|
||||
import com.bwie.common.result.Result;
|
||||
import com.bwie.coupon.service.OrderService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/order")
|
||||
public class OrderController {
|
||||
|
||||
@Autowired
|
||||
private OrderService orderService;
|
||||
|
||||
/**
|
||||
* 添加卖出券码记录
|
||||
* @param order
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/add")
|
||||
public Result<String> addOrder(@RequestBody Order order){
|
||||
orderService.addOrder(order);
|
||||
return Result.success(null,"添加成功");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.bwie.coupon.controller;
|
||||
|
||||
import com.bwie.common.domain.Purchase;
|
||||
import com.bwie.common.domain.response.PurchaseResp;
|
||||
import com.bwie.common.result.Result;
|
||||
import com.bwie.coupon.service.PurchaseService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/purchase")
|
||||
public class PurchaseController {
|
||||
|
||||
@Autowired
|
||||
private PurchaseService purchaseService;
|
||||
|
||||
/**
|
||||
* 添加购入订单
|
||||
* @param purchase
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/addPurchase")
|
||||
public Result<String> addPurchase(@RequestBody Purchase purchase){
|
||||
purchaseService.addPurchase(purchase);
|
||||
return Result.success(null,"下单券码支付成功");
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看个人购入所有订单
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/list")
|
||||
public Result<List<PurchaseResp>> purchaseList() {
|
||||
return Result.success(purchaseService.purchaseList(),"查询成功");
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改购入订单状态
|
||||
* @param purchase
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/updStates")
|
||||
public Result<String> updStates(@RequestBody Purchase purchase){
|
||||
purchaseService.updStates(purchase);
|
||||
return Result.success(null,"修改状态成功");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.bwie.coupon.controller;
|
||||
|
||||
import com.bwie.common.domain.Stash;
|
||||
import com.bwie.common.domain.request.StashReq;
|
||||
import com.bwie.common.domain.response.StashResp;
|
||||
import com.bwie.common.result.Result;
|
||||
import com.bwie.coupon.service.StashService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/stash")
|
||||
public class StashController {
|
||||
|
||||
@Autowired
|
||||
private StashService stashService;
|
||||
|
||||
/**
|
||||
* 展示个人拥有的券码
|
||||
* @param stashReq
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/list")
|
||||
public Result<List<StashResp>> stashList(@RequestBody StashReq stashReq){
|
||||
return Result.success(stashService.stashList(stashReq),"查询成功");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.bwie.coupon.feign;
|
||||
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.result.Result;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
|
||||
@FeignClient("bwie-user")
|
||||
public interface UserFeign {
|
||||
|
||||
@PostMapping("/user/reduceUserMoney")
|
||||
public Result<String> reduceUserMoney(@RequestBody User user);
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.bwie.coupon.feign.factory;
|
||||
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.result.Result;
|
||||
import com.bwie.coupon.feign.UserFeign;
|
||||
import org.springframework.cloud.openfeign.FallbackFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class UserFactory implements FallbackFactory<UserFeign> {
|
||||
@Override
|
||||
public UserFeign create(Throwable cause) {
|
||||
return new UserFeign() {
|
||||
@Override
|
||||
public Result<String> reduceUserMoney(User user) {
|
||||
return Result.error("网络走丢了");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.bwie.coupon.mapper;
|
||||
|
||||
import com.bwie.common.domain.Coupon;
|
||||
import com.bwie.common.domain.response.CouponResp;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface CouponMapper {
|
||||
List<CouponResp> couponList();
|
||||
|
||||
void updNum(@Param("couponId") Integer couponId);
|
||||
|
||||
void reduceNum(@Param("couponId") Integer couponId);
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.bwie.coupon.mapper;
|
||||
|
||||
import com.bwie.common.domain.Order;
|
||||
import com.bwie.common.domain.User;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
@Mapper
|
||||
public interface OrderMapper {
|
||||
int addOrder(Order order);
|
||||
|
||||
Order selectOrder(@Param("couponId") Integer couponId);
|
||||
|
||||
void updOrderStatus(Order order);
|
||||
|
||||
User selectUser(@Param("orderId") Integer orderId);
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.bwie.coupon.mapper;
|
||||
|
||||
import com.bwie.common.domain.Middle;
|
||||
import com.bwie.common.domain.Purchase;
|
||||
import com.bwie.common.domain.response.PurchaseResp;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface PurchaseMapper {
|
||||
|
||||
|
||||
void addPurchase(Purchase purchase);
|
||||
|
||||
List<PurchaseResp> purchaseList(@Param("userId") Integer userId);
|
||||
|
||||
int updStates(Purchase purchase);
|
||||
|
||||
void addMiddle(@Param("orderId") Integer orderId, @Param("purchaseId") Integer purchaseId, @Param("couponId") Integer couponId);
|
||||
|
||||
Middle MiddleSelectMiddle(Purchase purchase);
|
||||
|
||||
List<Purchase> selectOutTime();
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.bwie.coupon.mapper;
|
||||
|
||||
import com.bwie.common.domain.Stash;
|
||||
import com.bwie.common.domain.request.StashReq;
|
||||
import com.bwie.common.domain.response.StashResp;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface StashMapper {
|
||||
List<StashResp> stashList(StashReq stashReq);
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.bwie.coupon.scheduled;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.bwie.common.constants.TokenConstants;
|
||||
import com.bwie.common.domain.Purchase;
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.domain.response.PurchaseResp;
|
||||
import com.bwie.common.utils.JwtUtils;
|
||||
import com.bwie.coupon.mapper.PurchaseMapper;
|
||||
import com.bwie.coupon.service.OrderService;
|
||||
import com.bwie.coupon.service.impl.OrderServiceImpl;
|
||||
import com.bwie.coupon.service.impl.PurchaseServiceImpl;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
@Log4j2
|
||||
public class UserScheduled {
|
||||
|
||||
|
||||
@Autowired
|
||||
private PurchaseMapper purchaseMapper;
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
|
||||
@Scheduled(cron = "0 * * * * ?")
|
||||
public void userScheduled(){
|
||||
List<Purchase> list = purchaseMapper.selectOutTime();
|
||||
log.info("总共有{}个超过二十四小时没有确定收货的",list.size());
|
||||
if(list.size()>0){
|
||||
for (Purchase purchase : list) {
|
||||
purchase.setPurchaseStates(2);
|
||||
purchaseMapper.updStates(purchase);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public User getInfo() {
|
||||
String token = request.getHeader(TokenConstants.TOKEN);
|
||||
String userKey = JwtUtils.getUserKey(token);
|
||||
String user = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
|
||||
return JSON.parseObject(user,User.class);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.bwie.coupon.service;
|
||||
|
||||
import com.bwie.common.domain.Coupon;
|
||||
import com.bwie.common.domain.response.CouponResp;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface CouponService {
|
||||
List<CouponResp> couponList();
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.bwie.coupon.service;
|
||||
|
||||
import com.bwie.common.domain.Order;
|
||||
|
||||
public interface OrderService {
|
||||
void addOrder(Order order);
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.bwie.coupon.service;
|
||||
|
||||
import com.bwie.common.domain.Purchase;
|
||||
import com.bwie.common.domain.response.PurchaseResp;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PurchaseService {
|
||||
void addPurchase(Purchase purchase);
|
||||
|
||||
List<PurchaseResp> purchaseList();
|
||||
|
||||
void updStates(Purchase purchase);
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.bwie.coupon.service;
|
||||
|
||||
import com.bwie.common.domain.Stash;
|
||||
import com.bwie.common.domain.request.StashReq;
|
||||
import com.bwie.common.domain.response.StashResp;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface StashService {
|
||||
List<StashResp> stashList(StashReq stashReq);
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.bwie.coupon.service.impl;
|
||||
|
||||
import com.bwie.common.domain.Coupon;
|
||||
import com.bwie.common.domain.response.CouponResp;
|
||||
import com.bwie.coupon.mapper.CouponMapper;
|
||||
import com.bwie.coupon.service.CouponService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class CouponServiceImpl implements CouponService {
|
||||
|
||||
@Autowired
|
||||
private CouponMapper couponMapper;
|
||||
|
||||
@Override
|
||||
public List<CouponResp> couponList() {
|
||||
return couponMapper.couponList();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
package com.bwie.coupon.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.bwie.common.constants.TokenConstants;
|
||||
import com.bwie.common.domain.Order;
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.utils.JwtUtils;
|
||||
import com.bwie.coupon.mapper.CouponMapper;
|
||||
import com.bwie.coupon.mapper.OrderMapper;
|
||||
import com.bwie.coupon.service.OrderService;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class OrderServiceImpl implements OrderService {
|
||||
|
||||
@Autowired
|
||||
private OrderMapper orderMapper;
|
||||
@Autowired
|
||||
private CouponMapper couponMapper;
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void addOrder(Order order) {
|
||||
//添加售卖券码订单记录
|
||||
order.setOrderId(getInfo().getUserId());
|
||||
int i = orderMapper.addOrder(order);
|
||||
if(i<=0){
|
||||
throw new RuntimeException("添加记录失败");
|
||||
}
|
||||
//缓存到redis当中
|
||||
redisTemplate.opsForSet().add("order",JSON.toJSONString(order));
|
||||
//增加对应的券码数量 +1
|
||||
couponMapper.updNum(order.getCouponId());
|
||||
//更新es
|
||||
String str = "啊";
|
||||
rabbitTemplate.convertAndSend("updEsList",str,message -> {
|
||||
message.getMessageProperties().setMessageId(UUID.randomUUID().toString());
|
||||
return message;
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
public User getInfo() {
|
||||
String token = request.getHeader(TokenConstants.TOKEN);
|
||||
String userKey = JwtUtils.getUserKey(token);
|
||||
String user = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
|
||||
return JSON.parseObject(user,User.class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
package com.bwie.coupon.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.bwie.common.constants.TokenConstants;
|
||||
import com.bwie.common.domain.Middle;
|
||||
import com.bwie.common.domain.Order;
|
||||
import com.bwie.common.domain.Purchase;
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.domain.response.PurchaseResp;
|
||||
import com.bwie.common.utils.JwtUtils;
|
||||
import com.bwie.coupon.feign.UserFeign;
|
||||
import com.bwie.coupon.mapper.CouponMapper;
|
||||
import com.bwie.coupon.mapper.OrderMapper;
|
||||
import com.bwie.coupon.mapper.PurchaseMapper;
|
||||
import com.bwie.coupon.service.OrderService;
|
||||
import com.bwie.coupon.service.PurchaseService;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class PurchaseServiceImpl implements PurchaseService {
|
||||
|
||||
@Autowired
|
||||
private PurchaseMapper purchaseMapper;
|
||||
@Autowired
|
||||
private CouponMapper couponMapper;
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
@Autowired
|
||||
private OrderMapper orderMapper;
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
@Resource
|
||||
private UserFeign userFeign;
|
||||
|
||||
@Override
|
||||
public void addPurchase(Purchase purchase) {
|
||||
purchase.setUserId(getInfo().getUserId());
|
||||
//添加购入订单
|
||||
purchaseMapper.addPurchase(purchase);
|
||||
//拿到购入券码最早售出的一张
|
||||
Order order = orderMapper.selectOrder(purchase.getCouponId());
|
||||
//判断是否还有客户售出的券码
|
||||
if(order!=null){
|
||||
order.setOrderStatus(1);
|
||||
orderMapper.updOrderStatus(order);
|
||||
purchaseMapper.addMiddle(order.getOrderId(),purchase.getPurchaseId(),order.getCouponId());
|
||||
}
|
||||
//购买成功扣除用户的金额及库存数量
|
||||
User user = new User();
|
||||
user.setUserId(purchase.getUserId());
|
||||
user.setUserPrice(purchase.getPurchasePrice());
|
||||
userFeign.reduceUserMoney(user);
|
||||
couponMapper.reduceNum(purchase.getCouponId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<PurchaseResp> purchaseList() {
|
||||
return purchaseMapper.purchaseList(getInfo().getUserId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void updStates(Purchase purchase) {
|
||||
//修改订单状态
|
||||
int i = purchaseMapper.updStates(purchase);
|
||||
if(i<=0){
|
||||
throw new RuntimeException("修改失败");
|
||||
}
|
||||
//查询添加订单时拿到的出售券码的中间记录表
|
||||
Middle middle = purchaseMapper.MiddleSelectMiddle(purchase);
|
||||
if(middle!=null){
|
||||
//修改状态
|
||||
Order order = new Order();
|
||||
order.setOrderId(middle.getOrderId());
|
||||
//订单完成
|
||||
order.setOrderStatus(4);
|
||||
orderMapper.updOrderStatus(order);
|
||||
User user = orderMapper.selectUser(middle.getOrderId());
|
||||
user.setUserPrice(purchase.getPurchasePrice());
|
||||
//发送redis异步给出售人加余额
|
||||
rabbitTemplate.convertAndSend("addUserMoney",user,message -> {
|
||||
message.getMessageProperties().setMessageId(UUID.randomUUID().toString());
|
||||
return message;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public User getInfo() {
|
||||
String token = request.getHeader(TokenConstants.TOKEN);
|
||||
String userKey = JwtUtils.getUserKey(token);
|
||||
String user = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
|
||||
return JSON.parseObject(user,User.class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.bwie.coupon.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.bwie.common.constants.TokenConstants;
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.domain.request.StashReq;
|
||||
import com.bwie.common.domain.response.StashResp;
|
||||
import com.bwie.common.utils.JwtUtils;
|
||||
import com.bwie.coupon.mapper.StashMapper;
|
||||
import com.bwie.coupon.service.StashService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class StashServiceImpl implements StashService {
|
||||
|
||||
@Autowired
|
||||
private StashMapper stashMapper;
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
|
||||
@Override
|
||||
public List<StashResp> stashList(StashReq stashReq) {
|
||||
stashReq.setUserId(getInfo().getUserId());
|
||||
return stashMapper.stashList(stashReq);
|
||||
}
|
||||
|
||||
public User getInfo() {
|
||||
String token = request.getHeader(TokenConstants.TOKEN);
|
||||
String userKey = JwtUtils.getUserKey(token);
|
||||
String user = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
|
||||
return JSON.parseObject(user,User.class);
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
# Tomcat
|
||||
server:
|
||||
port: 9008
|
||||
# Spring
|
||||
spring:
|
||||
rabbitmq:
|
||||
host: 47.102.213.213
|
||||
port: 5672
|
||||
username: guest
|
||||
password: guest
|
||||
virtual-host: /
|
||||
listener:
|
||||
simple:
|
||||
prefetch: 1 # 默认每次取出一条消息消费, 消费完成取下一条
|
||||
acknowledge-mode: manual # 设置消费端手动ack确认
|
||||
retry:
|
||||
enabled: true # 是否支持重试
|
||||
publisher-confirm-type: correlated #确认消息已发送到交换机(Exchange)
|
||||
publisher-returns: true #确认消息已发送到队列(Queue)
|
||||
main:
|
||||
allow-circular-references: true
|
||||
jackson:
|
||||
date-format: yyyy-MM-dd HH:mm:ss
|
||||
time-zone: GMT+8
|
||||
application:
|
||||
# 应用名称
|
||||
name: bwie-coupon
|
||||
profiles:
|
||||
# 环境配置
|
||||
active: dev
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
# 服务注册地址
|
||||
server-addr: 47.102.213.213:8848
|
||||
namespace: csh
|
||||
config:
|
||||
# 配置中心地址
|
||||
server-addr: 47.102.213.213:8848
|
||||
# 配置文件格式
|
||||
file-extension: yml
|
||||
# 共享配置
|
||||
shared-configs:
|
||||
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
|
||||
namespace: csh
|
||||
fdfs:
|
||||
so-timeout: 1500 # socket 连接时长
|
||||
connect-timeout: 600 # 连接 tracker 服务器超时时长
|
||||
# 这两个是你服务器的 IP 地址,注意 23000 端口也要打开,阿里云服务器记得配置安全组。tracker 要和 stroage 服务进行交流
|
||||
tracker-list: 47.102.213.213:22122
|
||||
web-server-url: 47.102.213.213:8888
|
||||
pool:
|
||||
jmx-enabled: false
|
||||
# 生成缩略图
|
||||
thumb-image:
|
||||
height: 500
|
||||
width: 500
|
|
@ -0,0 +1,18 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.bwie.coupon.mapper.CouponMapper">
|
||||
<update id="updNum">
|
||||
update coupon set coupon_num = coupon_num+1 where coupon_id = #{couponId}
|
||||
</update>
|
||||
<update id="reduceNum">
|
||||
update coupon set coupon_num = coupon_num-1 where coupon_id = #{couponId}
|
||||
</update>
|
||||
|
||||
|
||||
<select id="couponList" resultType="com.bwie.common.domain.response.CouponResp">
|
||||
select * from coupon
|
||||
left join type on coupon.type_id = type.type_id
|
||||
</select>
|
||||
</mapper>
|
|
@ -0,0 +1,22 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.bwie.coupon.mapper.OrderMapper">
|
||||
|
||||
|
||||
<insert id="addOrder" keyProperty="orderId" useGeneratedKeys="true">
|
||||
INSERT INTO `g6-month`.`order` (`order_id`, `coupon_id`, `transfer_time`, `end_time`, `order_status`, `user_id`)
|
||||
VALUES (0,#{couponId},#{transferTime},#{endTime},0,#{userId})
|
||||
</insert>
|
||||
<update id="updOrderStatus">
|
||||
update `order` set order_status = #{orderStatus} where order_id = #{orderId}
|
||||
</update>
|
||||
|
||||
<select id="selectOrder" resultType="com.bwie.common.domain.Order">
|
||||
select * from `order` where coupon_id = #{couponId} and order_status =0 limit 1
|
||||
</select>
|
||||
<select id="selectUser" resultType="com.bwie.common.domain.User">
|
||||
select * from user where user_id = (select user_id from `order` where order_id = #{orderId})
|
||||
</select>
|
||||
</mapper>
|
|
@ -0,0 +1,32 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.bwie.coupon.mapper.PurchaseMapper">
|
||||
|
||||
<insert id="addPurchase" useGeneratedKeys="true" keyProperty="purchaseId">
|
||||
insert into purchase values(0,#{couponId},now(),#{purchasePrice},1,#{userId})
|
||||
</insert>
|
||||
<insert id="addMiddle">
|
||||
insert into middle values(0,#{orderId},#{purchaseId},#{couponId})
|
||||
</insert>
|
||||
|
||||
<update id="updStates">
|
||||
update purchase set purchase_states = #{purchaseStates} where purchase_id = #{purchaseId}
|
||||
</update>
|
||||
|
||||
<select id="purchaseList" resultType="com.bwie.common.domain.response.PurchaseResp">
|
||||
select * from purchase p
|
||||
left join coupon c on p.coupon_id = c.coupon_id
|
||||
left join type t on c.type_id = t.type_id
|
||||
left join sort s on c.sort_id = s.sort_id
|
||||
where p.user_id = #{userId}
|
||||
</select>
|
||||
<select id="MiddleSelectMiddle" resultType="com.bwie.common.domain.Middle">
|
||||
select * from middle where purchase_id = #{purchaseId} and coupon_id = #{couponId}
|
||||
</select>
|
||||
<select id="selectOutTime" resultType="com.bwie.common.domain.Purchase">
|
||||
select * from purchase where TIMESTAMPDIFF(hour,now(),create_time)>24 and purchase_states = 1
|
||||
</select>
|
||||
|
||||
</mapper>
|
|
@ -0,0 +1,20 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.bwie.coupon.mapper.StashMapper">
|
||||
|
||||
|
||||
<select id="stashList" resultType="com.bwie.common.domain.response.StashResp">
|
||||
select * from stash s
|
||||
left join coupon c on s.coupon_id = c.coupon_id
|
||||
left join type t on c.type_id = t.type_id
|
||||
where s.user_id = #{userId}
|
||||
<if test="sortId !=null and sortId!=''">
|
||||
and c.sort_id = #{sortId}
|
||||
</if>
|
||||
<if test="typeId !=null and typeId!=''">
|
||||
and c.type_id = #{typeId}
|
||||
</if>
|
||||
</select>
|
||||
</mapper>
|
|
@ -0,0 +1,45 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.bwie</groupId>
|
||||
<artifactId>last-month</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<artifactId>bwie-es</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<!-- 引入 公共模块 -->
|
||||
<dependency>
|
||||
<groupId>com.bwie</groupId>
|
||||
<artifactId>bwie-common</artifactId>
|
||||
</dependency>
|
||||
<!-- Web应用程序的依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<!-- ES进行交互 -->
|
||||
<dependency>
|
||||
<groupId>org.elasticsearch.client</groupId>
|
||||
<artifactId>elasticsearch-rest-high-level-client</artifactId>
|
||||
</dependency>
|
||||
<!-- Lombok 简化Java代码的编写 -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<!-- test 测试依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,15 @@
|
|||
package com.bwie;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableFeignClients
|
||||
@EnableScheduling
|
||||
public class EsApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(EsApplication.class,args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.bwie.es.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;
|
||||
|
||||
|
||||
@Component
|
||||
public class ConfirmCallbackConfig implements RabbitTemplate.ConfirmCallback {
|
||||
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
/**
|
||||
* 当前bean初始化的时候执行
|
||||
*/
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.rabbitTemplate.setConfirmCallback(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认方法
|
||||
* @param correlationData correlation data for the callback.
|
||||
* @param ack true for ack, false for nack
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
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.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "es")
|
||||
@Data
|
||||
public class EsConfigInit {
|
||||
|
||||
private String host;
|
||||
private int port;
|
||||
private String scheme;
|
||||
|
||||
|
||||
@Bean// RestHighLevelClient 用来 做 es 操作
|
||||
public RestHighLevelClient initRestHighLevelClient(){
|
||||
|
||||
return new RestHighLevelClient(RestClient.builder(new HttpHost(host,port,scheme)));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.bwie.es.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
|
||||
*/
|
||||
@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.virtual-host}")
|
||||
private String virtualhost;
|
||||
|
||||
@Bean
|
||||
public ConnectionFactory connectionFactory() {
|
||||
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
|
||||
connectionFactory.setAddresses(host);
|
||||
connectionFactory.setUsername(username);
|
||||
connectionFactory.setPassword(password);
|
||||
connectionFactory.setVirtualHost(virtualhost);
|
||||
// 配置发送确认回调时,次配置必须配置,否则即使在RabbitTemplate配置了ConfirmCallback也不会生效
|
||||
connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
|
||||
connectionFactory.setPublisherReturns(true);
|
||||
return connectionFactory;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* rabbitAdmin
|
||||
* @param connectionFactory
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
|
||||
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
|
||||
rabbitAdmin.setAutoStartup(true);
|
||||
return rabbitAdmin;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.bwie.es.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 {
|
||||
// 消息转换配置
|
||||
@Bean
|
||||
public MessageConverter jsonMessageConverter(){
|
||||
return new Jackson2JsonMessageConverter();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.bwie.es.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;
|
||||
|
||||
|
||||
@Component
|
||||
public class ReturnsCallbackConfig implements RabbitTemplate.ReturnsCallback {
|
||||
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
/**
|
||||
* 当前bean初始化的时候执行
|
||||
*/
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.rabbitTemplate.setReturnsCallback(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息发送达到 queue 失败执行
|
||||
*
|
||||
* @param returnedMessage the returned message and metadata.
|
||||
*/
|
||||
@Override
|
||||
public void returnedMessage(ReturnedMessage returnedMessage) {
|
||||
System.out.println("消息" + returnedMessage.getMessage().toString() +
|
||||
"被交换机" + returnedMessage.getExchange() + "回退!"
|
||||
+ "退回原因为:" + returnedMessage.getReplyText());
|
||||
// TODO 回退了所有的信息,可做补偿机制
|
||||
}
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.bwie.es.consumer;
|
||||
|
||||
import com.bwie.common.domain.response.CouponResp;
|
||||
import com.bwie.common.result.Result;
|
||||
import com.bwie.es.feign.CouponFeign;
|
||||
import com.bwie.es.service.EsService;
|
||||
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.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
@Log4j2
|
||||
public class UpdEsList {
|
||||
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
@Resource
|
||||
private CouponFeign couponFeign;
|
||||
@Autowired
|
||||
private EsService esService;
|
||||
|
||||
|
||||
|
||||
@RabbitListener(queuesToDeclare = {@Queue("updEsList")})
|
||||
public void updEsList(String str,Message message, Channel channel){
|
||||
Long aLong = redisTemplate.opsForSet().add("messageId", message.getMessageProperties().getMessageId());
|
||||
if(aLong!=null && aLong == 1){
|
||||
List<CouponResp> couponResps = couponFeign.couponList().getData();
|
||||
esService.deleteAll();
|
||||
esService.batchAdd(couponResps);
|
||||
log.info("同步成功!!!!!!!!");
|
||||
try {
|
||||
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
|
||||
} catch (IOException e) {
|
||||
try {
|
||||
redisTemplate.opsForSet().remove("messageId",message.getMessageProperties().getMessageId());
|
||||
channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
|
||||
} catch (IOException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.bwie.es.controller;
|
||||
|
||||
import com.bwie.common.domain.Coupon;
|
||||
import com.bwie.common.domain.request.EsReq;
|
||||
import com.bwie.common.domain.response.CouponResp;
|
||||
import com.bwie.common.result.Result;
|
||||
import com.bwie.es.service.EsService;
|
||||
import org.elasticsearch.action.search.SearchRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/es")
|
||||
public class EsController {
|
||||
|
||||
@Autowired
|
||||
private EsService esService;
|
||||
|
||||
/**
|
||||
* 查询es列表
|
||||
* @param esReq
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/list")
|
||||
public Result<List<CouponResp>> esList(@RequestBody EsReq esReq){
|
||||
return Result.success(esService.esList(esReq),"查询成功");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.bwie.es.feign;
|
||||
|
||||
import com.bwie.common.domain.Coupon;
|
||||
import com.bwie.common.domain.response.CouponResp;
|
||||
import com.bwie.common.result.Result;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@FeignClient("bwie-coupon")
|
||||
public interface CouponFeign {
|
||||
|
||||
@GetMapping("/coupon/list")
|
||||
public Result<List<CouponResp>> couponList();
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.bwie.es.feign.factory;
|
||||
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.domain.response.CouponResp;
|
||||
import com.bwie.common.result.Result;
|
||||
import com.bwie.es.feign.CouponFeign;
|
||||
import org.springframework.cloud.openfeign.FallbackFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class CouponFactory implements FallbackFactory<CouponFeign> {
|
||||
@Override
|
||||
public CouponFeign create(Throwable cause) {
|
||||
return new CouponFeign() {
|
||||
@Override
|
||||
public Result<List<CouponResp>> couponList() {
|
||||
return Result.error("网络走丢了");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.bwie.es.service;
|
||||
|
||||
import com.bwie.common.domain.Coupon;
|
||||
import com.bwie.common.domain.request.EsReq;
|
||||
import com.bwie.common.domain.response.CouponResp;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface EsService {
|
||||
void batchAdd(List<CouponResp> couponList);
|
||||
|
||||
void deleteAll();
|
||||
|
||||
List<CouponResp> esList(EsReq esReq);
|
||||
}
|
|
@ -0,0 +1,129 @@
|
|||
package com.bwie.es.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.bwie.common.domain.Coupon;
|
||||
import com.bwie.common.domain.request.EsReq;
|
||||
import com.bwie.common.domain.response.CouponResp;
|
||||
import com.bwie.common.utils.StringUtils;
|
||||
import com.bwie.es.feign.CouponFeign;
|
||||
import com.bwie.es.service.EsService;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.apache.lucene.util.QueryBuilder;
|
||||
import org.elasticsearch.action.bulk.BulkRequest;
|
||||
import org.elasticsearch.action.index.IndexRequest;
|
||||
import org.elasticsearch.action.search.SearchRequest;
|
||||
import org.elasticsearch.action.search.SearchRequestBuilder;
|
||||
import org.elasticsearch.action.search.SearchResponse;
|
||||
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.QueryBuilders;
|
||||
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
|
||||
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.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@Log4j2
|
||||
public class EsServiceImpl implements EsService {
|
||||
|
||||
@Autowired
|
||||
private RestHighLevelClient restHighLevelClient;
|
||||
|
||||
private static final String INDEX_NAME = "coupon";
|
||||
|
||||
|
||||
@Override
|
||||
public List<CouponResp> esList(EsReq esReq) {
|
||||
ArrayList<CouponResp> couponArrayList = new ArrayList<>();
|
||||
long total;
|
||||
try {
|
||||
SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
|
||||
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
|
||||
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
|
||||
if(StringUtils.isNotBlank(esReq.getCouponName())){
|
||||
boolQueryBuilder.must(QueryBuilders.matchQuery("couponName",esReq.getCouponName()));
|
||||
}
|
||||
if(esReq.getTypeId()!=0){
|
||||
boolQueryBuilder.must(QueryBuilders.matchQuery("typeId",esReq.getTypeId()));
|
||||
}
|
||||
if(esReq.getSortId()!=0){
|
||||
boolQueryBuilder.must(QueryBuilders.matchQuery("sortId",esReq.getSortId()));
|
||||
}
|
||||
searchSourceBuilder.query(boolQueryBuilder);
|
||||
searchSourceBuilder.highlighter(
|
||||
new HighlightBuilder()
|
||||
.field("couponName")
|
||||
.preTags("<span style= \" color:red; \" >")
|
||||
.postTags("</span>")
|
||||
);
|
||||
searchRequest.source(searchSourceBuilder);
|
||||
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
|
||||
SearchHits hits = search.getHits();
|
||||
total = hits.getTotalHits().value;
|
||||
SearchHit[] hitsHits = hits.getHits();
|
||||
for (SearchHit hitsHit : hitsHits) {
|
||||
String sourceAsString = hitsHit.getSourceAsString();
|
||||
CouponResp couponResp = JSON.parseObject(sourceAsString, CouponResp.class);
|
||||
Map<String, HighlightField> highlightFields = hitsHit.getHighlightFields();
|
||||
if(highlightFields != null){
|
||||
HighlightField couponNames = highlightFields.get("couponName");
|
||||
if(couponNames != null){
|
||||
Text[] fragments = couponNames.getFragments();
|
||||
String str = "";
|
||||
for (Text fragment : fragments) {
|
||||
str+=fragment;
|
||||
}
|
||||
couponResp.setCouponName(str);
|
||||
}
|
||||
}
|
||||
couponArrayList.add(couponResp);
|
||||
}
|
||||
return couponArrayList;
|
||||
} catch (IOException e) {
|
||||
log.info("查询失败");
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void batchAdd(List<CouponResp> couponList) {
|
||||
BulkRequest bulkRequest = new BulkRequest();
|
||||
couponList.forEach(coupon -> {
|
||||
bulkRequest.add(new IndexRequest(INDEX_NAME)
|
||||
.id(coupon.getCouponId())
|
||||
.source(JSON.toJSONString(coupon), XContentType.JSON));
|
||||
});
|
||||
try {
|
||||
restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteAll() {
|
||||
DeleteByQueryRequest queryRequest = new DeleteByQueryRequest(INDEX_NAME);
|
||||
queryRequest.setQuery(QueryBuilders.matchAllQuery());
|
||||
try {
|
||||
restHighLevelClient.deleteByQuery(queryRequest,RequestOptions.DEFAULT);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.bwie.es.sync;
|
||||
|
||||
import com.bwie.common.domain.Coupon;
|
||||
import com.bwie.common.domain.response.CouponResp;
|
||||
import com.bwie.es.feign.CouponFeign;
|
||||
import com.bwie.es.service.EsService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class CouponSync implements ApplicationRunner {
|
||||
|
||||
@Autowired
|
||||
private CouponFeign couponFeign;
|
||||
|
||||
@Autowired
|
||||
private EsService esService;
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) throws Exception {
|
||||
//调用coupon列表
|
||||
List<CouponResp> couponList = couponFeign.couponList().getData();
|
||||
if(couponList.size()>0){
|
||||
// 先删除es里的内容
|
||||
esService.deleteAll();
|
||||
//再将从数据库查到的数据加入es当中
|
||||
esService.batchAdd(couponList);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@Scheduled(cron = "*/30 * * * * ?")
|
||||
public void text(){
|
||||
List<CouponResp> couponList = couponFeign.couponList().getData();
|
||||
if(couponList.size()>0){
|
||||
// 先删除es里的内容
|
||||
esService.deleteAll();
|
||||
//再将从数据库查到的数据加入es当中
|
||||
esService.batchAdd(couponList);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
# Tomcat
|
||||
server:
|
||||
port: 9006
|
||||
# Spring
|
||||
spring:
|
||||
rabbitmq:
|
||||
host: 47.102.213.213
|
||||
port: 5672
|
||||
username: guest
|
||||
password: guest
|
||||
virtual-host: /
|
||||
listener:
|
||||
simple:
|
||||
prefetch: 1 # 默认每次取出一条消息消费, 消费完成取下一条
|
||||
acknowledge-mode: manual # 设置消费端手动ack确认
|
||||
retry:
|
||||
enabled: true # 是否支持重试
|
||||
publisher-confirm-type: correlated #确认消息已发送到交换机(Exchange)
|
||||
publisher-returns: true #确认消息已发送到队列(Queue)
|
||||
elasticsearch:
|
||||
|
||||
rest:
|
||||
|
||||
uris: http://47.102.213.213:9200
|
||||
main:
|
||||
allow-circular-references: true
|
||||
jackson:
|
||||
date-format: yyyy-MM-dd HH:mm:ss
|
||||
time-zone: GMT+8
|
||||
application:
|
||||
# 应用名称
|
||||
name: bwie-es
|
||||
profiles:
|
||||
# 环境配置
|
||||
active: dev
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
# 服务注册地址
|
||||
server-addr: 47.102.213.213:8848
|
||||
namespace: csh
|
||||
config:
|
||||
# 配置中心地址
|
||||
server-addr: 47.102.213.213:8848
|
||||
# 配置文件格式
|
||||
file-extension: yml
|
||||
# 共享配置
|
||||
shared-configs:
|
||||
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
|
||||
namespace: csh
|
||||
es:
|
||||
hostname: 47.102.213.213
|
||||
port: 9200
|
||||
scheme: http
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.bwie</groupId>
|
||||
<artifactId>last-month</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<artifactId>bwie-rabbitmq</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.bwie</groupId>
|
||||
<artifactId>bwie-common</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<!-- 引入 rabbitMQ的依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-amqp</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
|
@ -0,0 +1,14 @@
|
|||
package com.bwie.rabbitmq;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableFeignClients
|
||||
public class RabbitmqApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(RabbitmqApplication.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.bwie.rabbitmq.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;
|
||||
|
||||
|
||||
@Component
|
||||
public class ConfirmCallbackConfig implements RabbitTemplate.ConfirmCallback {
|
||||
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
/**
|
||||
* 当前bean初始化的时候执行
|
||||
*/
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.rabbitTemplate.setConfirmCallback(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认方法
|
||||
* @param correlationData correlation data for the callback.
|
||||
* @param ack true for ack, false for nack
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.bwie.rabbitmq.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
|
||||
*/
|
||||
@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.virtual-host}")
|
||||
private String virtualhost;
|
||||
|
||||
@Bean
|
||||
public ConnectionFactory connectionFactory() {
|
||||
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
|
||||
connectionFactory.setAddresses(host);
|
||||
connectionFactory.setUsername(username);
|
||||
connectionFactory.setPassword(password);
|
||||
connectionFactory.setVirtualHost(virtualhost);
|
||||
// 配置发送确认回调时,次配置必须配置,否则即使在RabbitTemplate配置了ConfirmCallback也不会生效
|
||||
connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
|
||||
connectionFactory.setPublisherReturns(true);
|
||||
return connectionFactory;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* rabbitAdmin
|
||||
* @param connectionFactory
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
|
||||
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
|
||||
rabbitAdmin.setAutoStartup(true);
|
||||
return rabbitAdmin;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.bwie.rabbitmq.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 {
|
||||
// 消息转换配置
|
||||
@Bean
|
||||
public MessageConverter jsonMessageConverter(){
|
||||
return new Jackson2JsonMessageConverter();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.bwie.rabbitmq.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;
|
||||
|
||||
|
||||
@Component
|
||||
public class ReturnsCallbackConfig implements RabbitTemplate.ReturnsCallback {
|
||||
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
/**
|
||||
* 当前bean初始化的时候执行
|
||||
*/
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.rabbitTemplate.setReturnsCallback(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息发送达到 queue 失败执行
|
||||
*
|
||||
* @param returnedMessage the returned message and metadata.
|
||||
*/
|
||||
@Override
|
||||
public void returnedMessage(ReturnedMessage returnedMessage) {
|
||||
System.out.println("消息" + returnedMessage.getMessage().toString() +
|
||||
"被交换机" + returnedMessage.getExchange() + "回退!"
|
||||
+ "退回原因为:" + returnedMessage.getReplyText());
|
||||
// TODO 回退了所有的信息,可做补偿机制
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.bwie.rabbitmq.consumer;
|
||||
|
||||
import com.bwie.common.domain.User;
|
||||
import com.bwie.common.result.Result;
|
||||
import com.bwie.rabbitmq.feign.UserFeign;
|
||||
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.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
@Component
|
||||
@Log4j2
|
||||
public class AddUserMoney {
|
||||
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
@Resource
|
||||
private UserFeign userFeign;
|
||||
|
||||
@RabbitListener(queuesToDeclare = {@Queue("addUserMoney")})
|
||||
public void addUserMoney(User user, Message message, Channel channel){
|
||||
Long aLong = redisTemplate.opsForSet().add("messageId", message.getMessageProperties().getMessageId());
|
||||
if(aLong!=null && aLong == 1){
|
||||
Result<String> stringResult = userFeign.addUserMoney(user);
|
||||
if(200==stringResult.getCode()){
|
||||
log.info("添加金额成功");
|
||||
}
|
||||
try {
|
||||
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
|
||||
} catch (IOException e) {
|
||||
try {
|
||||
redisTemplate.opsForSet().remove("messageId",message.getMessageProperties().getMessageId());
|
||||
channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
|
||||
} catch (IOException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue