first commit
This commit is contained in:
commit
e73f60cc6b
18
README.md
Normal file
18
README.md
Normal file
@ -0,0 +1,18 @@
|
||||
# Read Me First
|
||||
|
||||
The following was discovered as part of building this project:
|
||||
|
||||
* The JVM level was changed from '1.8' to '17', review
|
||||
the [JDK Version Range](https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-Versions#jdk-version-range)
|
||||
on the wiki for more details.
|
||||
|
||||
# Getting Started
|
||||
|
||||
### Reference Documentation
|
||||
|
||||
For further reference, please consider the following sections:
|
||||
|
||||
* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html)
|
||||
* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/3.1.0/maven-plugin/reference/html/)
|
||||
* [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.1.0/maven-plugin/reference/html/#build-image)
|
||||
|
||||
7
baogutang-admin/Dockerfile
Normal file
7
baogutang-admin/Dockerfile
Normal file
@ -0,0 +1,7 @@
|
||||
FROM openjdk:8
|
||||
ENV TZ=Asia/Shanghai
|
||||
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
||||
COPY ./baogutang-admin/target/baogutang-admin-1.0.0-SNAPSHOT.jar /apps/baogutang-admin.jar
|
||||
WORKDIR /apps
|
||||
RUN bash -c 'touch /baogutang-admin.jar'
|
||||
CMD exec java $JAVA_OPTS -jar baogutang-admin.jar
|
||||
153
baogutang-admin/pom.xml
Normal file
153
baogutang-admin/pom.xml
Normal file
@ -0,0 +1,153 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>top.baogutang</groupId>
|
||||
<artifactId>baogutang-parent</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>baogutang-admin</artifactId>
|
||||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>top.baogutang</groupId>
|
||||
<artifactId>baogutang-common</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun.openservices</groupId>
|
||||
<artifactId>aliyun-log-logback-appender</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.protobuf</groupId>
|
||||
<artifactId>protobuf-java</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>dingtalk</artifactId>
|
||||
<version>2.0.20</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>2.2.5.RELEASE</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.19</version>
|
||||
<configuration>
|
||||
<skipTests>true</skipTests>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>local</id>
|
||||
<properties>
|
||||
<profileActive>local</profileActive>
|
||||
</properties>
|
||||
<activation>
|
||||
<activeByDefault>true</activeByDefault>
|
||||
</activation>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>test</id>
|
||||
<properties>
|
||||
<profileActive>test</profileActive>
|
||||
</properties>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>prod</id>
|
||||
<properties>
|
||||
<profileActive>prod</profileActive>
|
||||
</properties>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
|
||||
</project>
|
||||
@ -0,0 +1,23 @@
|
||||
package top.baogutang.admin;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
/**
|
||||
* @author nikooh
|
||||
*/
|
||||
@Slf4j
|
||||
@EnableScheduling
|
||||
@SpringBootApplication(scanBasePackages = "top.baogutang.*")
|
||||
@MapperScan(basePackages = {"top.baogutang.admin.dao.mapper", "top.baogutang.common.dao.mapper"})
|
||||
public class BaogutangAdminApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(BaogutangAdminApplication.class, args);
|
||||
log.info("<<<<<<<<<<<<<<<==BAO_GU_TANG后台管理服务启动成功!!!==>>>>>>>>>>>>>>>");
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,52 @@
|
||||
package top.baogutang.admin.domain;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/16 : 12:09
|
||||
*/
|
||||
@Data
|
||||
public class EdgeXAnnouncementsDto implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 2069054276884655439L;
|
||||
|
||||
/**
|
||||
* id
|
||||
*/
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 标题
|
||||
*/
|
||||
private String title;
|
||||
|
||||
/**
|
||||
* 类型
|
||||
*/
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 封面
|
||||
*/
|
||||
private String cover;
|
||||
|
||||
/**
|
||||
* 创作者
|
||||
*/
|
||||
private String creator;
|
||||
|
||||
/**
|
||||
* 内容
|
||||
*/
|
||||
private String content;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private Date createdAt;
|
||||
}
|
||||
@ -0,0 +1,59 @@
|
||||
package top.baogutang.admin.schedule;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.TypeReference;
|
||||
import com.zjiecode.wxpusher.client.bean.Message;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.collections.CollectionUtils;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.baogutang.admin.domain.EdgeXAnnouncementsDto;
|
||||
import top.baogutang.admin.services.IWxMsgPushService;
|
||||
import top.baogutang.common.domain.Page;
|
||||
import top.baogutang.common.domain.Results;
|
||||
import top.baogutang.common.properties.WxMsgPushProperties;
|
||||
import top.baogutang.common.utils.HttpUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @description: EDGEX公告
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/16 : 11:41
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RefreshScope
|
||||
public class EdgeXNoticeSchedule {
|
||||
|
||||
@Resource
|
||||
private IWxMsgPushService wxMsgPushService;
|
||||
|
||||
@Resource
|
||||
private WxMsgPushProperties wxMsgPushProperties;
|
||||
|
||||
/**
|
||||
* 每分钟查询edgeX公告
|
||||
*/
|
||||
@Scheduled(cron = "0 0/1 * * * ? ")
|
||||
public void edgeXNotice() {
|
||||
Results<Page<EdgeXAnnouncementsDto>> results = HttpUtils.get("https://art-api.edge-x.cn/api/v1/art/announcements?pageNum=1&pageSize=1", new TypeReference<Results<Page<EdgeXAnnouncementsDto>>>() {
|
||||
});
|
||||
log.info(">>>>>>>>>>请求获取edgeX公告返回数据:{}<<<<<<<<<<", JSON.toJSONString(results));
|
||||
if (Objects.isNull(results)) {
|
||||
return;
|
||||
}
|
||||
if (!Boolean.TRUE.equals(results.isSuccess())) {
|
||||
return;
|
||||
}
|
||||
if (Objects.isNull(results.getData()) || CollectionUtils.isEmpty(results.getData().getList())) {
|
||||
return;
|
||||
}
|
||||
EdgeXAnnouncementsDto announcementsDto = results.getData().getList().get(0);
|
||||
if (Math.abs(announcementsDto.getCreatedAt().getTime() - System.currentTimeMillis()) <= 60000) {
|
||||
wxMsgPushService.msgPush(Message.CONTENT_TYPE_HTML, announcementsDto.getTitle(), announcementsDto.getContent(), wxMsgPushProperties.getTopicIds());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,24 @@
|
||||
package top.baogutang.admin.services;
|
||||
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @description: 微信消息推送service
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/16 : 10:27
|
||||
*/
|
||||
public interface IWxMsgPushService {
|
||||
|
||||
/**
|
||||
* 微信消息推送
|
||||
*
|
||||
* @param msgType 消息类型
|
||||
* @param summary 消息主题
|
||||
* @param msgContent 消息内容
|
||||
* @param topicIdSet 消息模版id
|
||||
* @return 推送结果
|
||||
*/
|
||||
Boolean msgPush(Integer msgType, String summary, String msgContent, Set<Long> topicIdSet);
|
||||
|
||||
}
|
||||
@ -0,0 +1,81 @@
|
||||
package top.baogutang.admin.services.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.zjiecode.wxpusher.client.WxPusher;
|
||||
import com.zjiecode.wxpusher.client.bean.Message;
|
||||
import com.zjiecode.wxpusher.client.bean.MessageResult;
|
||||
import com.zjiecode.wxpusher.client.bean.Result;
|
||||
import com.zjiecode.wxpusher.client.bean.WxUser;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.collections.CollectionUtils;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.baogutang.admin.services.IWxMsgPushService;
|
||||
import com.zjiecode.wxpusher.client.bean.Page;
|
||||
import top.baogutang.common.exceptions.BusinessException;
|
||||
import top.baogutang.common.properties.WxMsgPushProperties;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/16 : 10:27
|
||||
*/
|
||||
@Slf4j
|
||||
@RefreshScope
|
||||
@Service
|
||||
public class WxMsgPushServiceImpl implements IWxMsgPushService {
|
||||
|
||||
@Resource
|
||||
private WxMsgPushProperties wxMsgPushProperties;
|
||||
|
||||
@Override
|
||||
public Boolean msgPush(Integer msgType, String summary, String msgContent, Set<Long> topicIdSet) {
|
||||
Message message = new Message();
|
||||
Set<String> userUidSet = this.queryUids(wxMsgPushProperties.getAppToken());
|
||||
if (CollectionUtils.isEmpty(userUidSet)) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
message.setUids(userUidSet);
|
||||
message.setAppToken(wxMsgPushProperties.getAppToken());
|
||||
message.setSummary(summary);
|
||||
message.setContentType(msgType);
|
||||
message.setContent(msgContent);
|
||||
Result<List<MessageResult>> result = null;
|
||||
try {
|
||||
result = WxPusher.send(message);
|
||||
} catch (Exception e) {
|
||||
log.error(">>>>>>>>>>推送消息异常:{}<<<<<<<<<<", e.getMessage(), e);
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
log.info(">>>>>>>>>>消息推送结果:{}<<<<<<<<<<", JSON.toJSONString(result));
|
||||
if (Objects.nonNull(result) && result.isSuccess()) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
|
||||
private Set<String> queryUids(String appToken) {
|
||||
//分页查询全部用户
|
||||
Result<Page<WxUser>> wxUsersResult = null;
|
||||
try {
|
||||
wxUsersResult = WxPusher.queryWxUser(appToken, 1, Integer.MAX_VALUE);
|
||||
} catch (Exception e) {
|
||||
log.error(">>>>>>>>>>查询用户信息失败:{}<<<<<<<<<<", e.getMessage(), e);
|
||||
throw new BusinessException("查询用户信息失败");
|
||||
}
|
||||
log.info(">>>>>>>>>>查询用户列表结果:{}<<<<<<<<<<", JSON.toJSONString(wxUsersResult));
|
||||
if (Objects.nonNull(wxUsersResult) && Objects.nonNull(wxUsersResult.getData()) && CollectionUtils.isNotEmpty(wxUsersResult.getData().getRecords())) {
|
||||
return wxUsersResult.getData().getRecords().stream()
|
||||
.map(WxUser::getUid)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
return Collections.emptySet();
|
||||
}
|
||||
}
|
||||
19
baogutang-admin/src/main/resources/bootstrap-local.yml
Normal file
19
baogutang-admin/src/main/resources/bootstrap-local.yml
Normal file
@ -0,0 +1,19 @@
|
||||
spring:
|
||||
application:
|
||||
name: baogutang-admin
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
server-addr: 42.51.4.235:8848
|
||||
config:
|
||||
server-addr: 42.51.4.235:8848
|
||||
namespace: adcc486c-d6fb-465a-a4f6-3fea7234433b
|
||||
file-extension: yml
|
||||
refresh-enabled: true
|
||||
group: DEFAULT_GROUP
|
||||
username: nacos
|
||||
password: 199312
|
||||
# shared-configs:
|
||||
# - data-id: goods-blindbox.yml
|
||||
# refresh: true
|
||||
|
||||
19
baogutang-admin/src/main/resources/bootstrap-prod.yml
Normal file
19
baogutang-admin/src/main/resources/bootstrap-prod.yml
Normal file
@ -0,0 +1,19 @@
|
||||
spring:
|
||||
application:
|
||||
name: baogutang-admin
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
server-addr: 42.51.4.235:8848
|
||||
config:
|
||||
server-addr: 42.51.4.235:8848
|
||||
namespace: 50b370f0-6fc9-4e1d-9a19-df276cff9eac
|
||||
file-extension: yml
|
||||
refresh-enabled: true
|
||||
group: DEFAULT_GROUP
|
||||
username: nacos
|
||||
password: 199312
|
||||
# shared-configs:
|
||||
# - data-id: goods-blindbox.yml
|
||||
# refresh: true
|
||||
|
||||
19
baogutang-admin/src/main/resources/bootstrap-test.yml
Normal file
19
baogutang-admin/src/main/resources/bootstrap-test.yml
Normal file
@ -0,0 +1,19 @@
|
||||
spring:
|
||||
application:
|
||||
name: baogutang-admin
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
server-addr: 42.51.4.235:8848
|
||||
config:
|
||||
server-addr: 42.51.4.235:8848
|
||||
namespace: 7e44b734-781d-4c21-a524-4bad1557d95f
|
||||
file-extension: yml
|
||||
refresh-enabled: true
|
||||
group: DEFAULT_GROUP
|
||||
username: nacos
|
||||
password: 199312
|
||||
# shared-configs:
|
||||
# - data-id: goods-blindbox.yml
|
||||
# refresh: true
|
||||
|
||||
5
baogutang-admin/src/main/resources/bootstrap.yml
Normal file
5
baogutang-admin/src/main/resources/bootstrap.yml
Normal file
@ -0,0 +1,5 @@
|
||||
spring:
|
||||
profiles:
|
||||
active: @profileActive@
|
||||
main:
|
||||
allow-bean-definition-overriding: true
|
||||
114
baogutang-admin/src/main/resources/logback-spring.xml
Normal file
114
baogutang-admin/src/main/resources/logback-spring.xml
Normal file
@ -0,0 +1,114 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration debug="false" scan="true" scanPeriod="1 seconds">
|
||||
<include resource="logback-default.xml"/>
|
||||
<contextName>logback</contextName>
|
||||
<springProperty scope="context" name="logStore" source="spring.application.name"/>
|
||||
<property name="log.path" value="/var/logs/${logStore}"/>
|
||||
|
||||
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} [%X{X-Request-Id}] [%thread] %-5level %logger - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${log.path}/app.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>${log.path}/%d{yyyy-MM-dd,aux}/app-%d{yyyy-MM-dd}.%i.log
|
||||
</fileNamePattern>
|
||||
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
|
||||
<maxFileSize>50MB</maxFileSize>
|
||||
</timeBasedFileNamingAndTriggeringPolicy>
|
||||
<!-- 保留最近60天的日志 -->
|
||||
<maxHistory>60</maxHistory>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%date{HH:mm:ss.SSS} [%X{X-Request-Id}] [%thread] %-5level %logger - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="asyncFileAppender" class="ch.qos.logback.classic.AsyncAppender">
|
||||
<queueSize>10000</queueSize>
|
||||
<discardingThreshold>0</discardingThreshold>
|
||||
<appender-ref ref="file"/>
|
||||
</appender>
|
||||
|
||||
<!-- 读取配置文件信息(交由各项目指定) -->
|
||||
<property name="active" value="${spring.profiles.active:-test}" />
|
||||
<property name="active" value="${env:-test}" />
|
||||
<springProperty scope="context" name="springEnv" source="spring.profiles.active" defaultValue="${active:-test}" />
|
||||
<springProperty scope="context" name="appEnv" source="server.application.logEnv" defaultValue="${springEnv:-test}" />
|
||||
<springProperty scope="context" name="appId" source="spring.application.name" defaultValue="localhost" />
|
||||
|
||||
<!--为了防止进程退出时,内存中的数据丢失,请加上此选项-->
|
||||
<shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook"/>
|
||||
|
||||
<!-- 外网 -->
|
||||
<appender name="ONLINE-OUT" class="com.aliyun.openservices.log.logback.LoghubAppender">
|
||||
<!--必选项 -->
|
||||
<endpoint>cn-shanghai.log.aliyuncs.com</endpoint>
|
||||
<accessKeyId>LTAI5tRN9T5Tz1QExcSpUaBc</accessKeyId>
|
||||
<accessKey>LniIMK15XEOc6Nn5mOrtX399FkVfQd</accessKey>
|
||||
<projectName>baogutang</projectName>
|
||||
<logstore>${appEnv}</logstore>
|
||||
|
||||
<!-- 可选项 -->
|
||||
<topic>${appId}</topic>
|
||||
<!-- <source>source1</source> -->
|
||||
|
||||
<!-- 可选项 详见 '参数说明' -->
|
||||
<packageTimeoutInMS>3000</packageTimeoutInMS>
|
||||
<logsCountPerPackage>4096</logsCountPerPackage>
|
||||
<logsBytesPerPackage>3145728</logsBytesPerPackage>
|
||||
<memPoolSizeInByte>104857600</memPoolSizeInByte>
|
||||
<retryTimes>3</retryTimes>
|
||||
<maxIOThreadSizeInPool>8</maxIOThreadSizeInPool>
|
||||
|
||||
<!-- 可选项 设置时区 -->
|
||||
<timeZone>Asia/Shanghai</timeZone>
|
||||
<!-- 可选项 设置时间格式 -->
|
||||
<timeFormat>yyyy-MM-dd HH:mm:ss.SSS</timeFormat>
|
||||
<!-- 可选项 通过配置 encoder 的 pattern 自定义 log 的格式 -->
|
||||
<encoder>
|
||||
<!-- <pattern>[${appId}] %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{0}: %msg</pattern> -->
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%X{X-Request-Id}] [%thread] %logger{0}: %msg</pattern>
|
||||
</encoder>
|
||||
|
||||
<!-- 指定级别的日志(INFO,WARN,ERROR) -->
|
||||
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
|
||||
<level>INFO</level>
|
||||
</filter>
|
||||
</appender>
|
||||
|
||||
<logger name="org.hibernate" level="ERROR" />
|
||||
<logger name="org.apache" level="ERROR" />
|
||||
<logger name="ch.qos.logback" level="WARN" />
|
||||
<logger name="org.elasticsearch" level="ERROR" />
|
||||
<logger name="org.mongodb.driver" level="INFO" />
|
||||
<logger name="springfox.documentation" level="WARN" />
|
||||
<logger name="com.aliyun.openservices.log" level="INFO" />
|
||||
<logger name="com" level="INFO"/>
|
||||
<logger name="top" level="INFO"/>
|
||||
<logger name="net" level="ERROR"/>
|
||||
<logger name="org" level="INFO"/>
|
||||
<logger name="io" level="INFO"/>
|
||||
<logger name="springfox" level="INFO"/>
|
||||
<logger name="Validator" level="INFO"/>
|
||||
<logger name="org.springframework" level="INFO"/>
|
||||
|
||||
|
||||
<springProfile name="test,prod">
|
||||
<root level="DEBUG">
|
||||
<appender-ref ref="console"/>
|
||||
<appender-ref ref="ONLINE-OUT"/>
|
||||
</root>
|
||||
</springProfile>
|
||||
|
||||
<springProfile name="local">
|
||||
<root level="DEBUG">
|
||||
<appender-ref ref="console"/>
|
||||
<appender-ref ref="ONLINE-OUT"/>
|
||||
</root>
|
||||
</springProfile>
|
||||
|
||||
</configuration>
|
||||
@ -0,0 +1,13 @@
|
||||
package top.baogutang.business.admin;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class BaogutangAdminApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
7
baogutang-business/Dockerfile
Normal file
7
baogutang-business/Dockerfile
Normal file
@ -0,0 +1,7 @@
|
||||
FROM openjdk:8
|
||||
ENV TZ=Asia/Shanghai
|
||||
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
||||
COPY ./baogutang-business/target/baogutang-business-1.0.0-SNAPSHOT.jar /apps/baogutang-business.jar
|
||||
WORKDIR /apps
|
||||
RUN bash -c 'touch /baogutang-business.jar'
|
||||
CMD exec java $JAVA_OPTS -jar baogutang-business.jar
|
||||
208
baogutang-business/pom.xml
Normal file
208
baogutang-business/pom.xml
Normal file
@ -0,0 +1,208 @@
|
||||
<?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>top.baogutang</groupId>
|
||||
<artifactId>baogutang-parent</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>baogutang-business</artifactId>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>top.baogutang</groupId>
|
||||
<artifactId>baogutang-common</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.yaml</groupId>
|
||||
<artifactId>snakeyaml</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun.openservices</groupId>
|
||||
<artifactId>aliyun-log-logback-appender</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.protobuf</groupId>
|
||||
<artifactId>protobuf-java</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
</dependency>
|
||||
<!-- testcase -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
</dependencies>
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
<excludes>
|
||||
<exclude>**/*.pfx</exclude>
|
||||
<exclude>**/*.cer</exclude>
|
||||
</excludes>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>false</filtering>
|
||||
<includes>
|
||||
<include>**/*.pfx</include>
|
||||
<include>**/*.cer</include>
|
||||
</includes>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>2.2.5.RELEASE</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<configuration>
|
||||
<encoding>UTF-8</encoding>
|
||||
<!-- 过滤后缀为pkcs12、jks的证书文件 -->
|
||||
<nonFilteredFileExtensions>
|
||||
<nonFilteredFileExtension>p12</nonFilteredFileExtension>
|
||||
<nonFilteredFileExtension>crt</nonFilteredFileExtension>
|
||||
</nonFilteredFileExtensions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.19</version>
|
||||
<configuration>
|
||||
<skipTests>true</skipTests>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.mybatis.generator</groupId>
|
||||
<artifactId>mybatis-generator-maven-plugin</artifactId>
|
||||
<version>1.4.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>io.github.javthon</groupId>
|
||||
<artifactId>mybatis-generator-yml-maven-plugin</artifactId>
|
||||
<version>0.0.1</version>
|
||||
<configuration>
|
||||
<configurationFile>src/main/resources/generatorConfig.yml</configurationFile>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>local</id>
|
||||
<properties>
|
||||
<profileActive>local</profileActive>
|
||||
</properties>
|
||||
<activation>
|
||||
<activeByDefault>true</activeByDefault>
|
||||
</activation>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>test</id>
|
||||
<properties>
|
||||
<profileActive>test</profileActive>
|
||||
</properties>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>prod</id>
|
||||
<properties>
|
||||
<profileActive>prod</profileActive>
|
||||
</properties>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
</project>
|
||||
@ -0,0 +1,22 @@
|
||||
package top.baogutang.business;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 11:22
|
||||
*/
|
||||
@Slf4j
|
||||
@SpringBootApplication(scanBasePackages = "top.baogutang.*")
|
||||
@MapperScan(basePackages = {"top.baogutang.business.dao.mapper", "top.baogutang.common.dao.mapper"})
|
||||
public class BaogutangBusinessApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(BaogutangBusinessApplication.class, args);
|
||||
log.info("<<<<<<<<<<<<<<<==BAO_GU_TANG客户端服务启动成功!!!==>>>>>>>>>>>>>>>");
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,23 @@
|
||||
package top.baogutang.business.controller;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.baogutang.common.domain.Results;
|
||||
|
||||
/**
|
||||
* @description: 回调控制器
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/16 : 10:10
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/callback")
|
||||
public class CallbackController {
|
||||
|
||||
|
||||
@RequestMapping("/wx/msgPush")
|
||||
public Results<String> wxMsgPushCallback() {
|
||||
return Results.ok(null);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
package top.baogutang.business.controller;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.servlet.view.RedirectView;
|
||||
import top.baogutang.business.services.IWxMsgPushService;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* @description: 微信消息推送控制器
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/16 : 10:24
|
||||
*/
|
||||
@Slf4j
|
||||
@Controller
|
||||
@RequestMapping("/api/v1/wx/msgPush")
|
||||
public class WxMsgPushController {
|
||||
|
||||
@Resource
|
||||
private IWxMsgPushService wxMsgPushService;
|
||||
|
||||
|
||||
/**
|
||||
* 创建一个带参数的二维码,用户扫码的时候,回调里面会携带二维码的参数.
|
||||
*
|
||||
* @return 二维码
|
||||
*/
|
||||
@GetMapping("/qrCode")
|
||||
public RedirectView getQrCode() {
|
||||
return new RedirectView(wxMsgPushService.getOrCode());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
package top.baogutang.business.services;
|
||||
|
||||
|
||||
/**
|
||||
* @description: 微信消息推送service
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/16 : 10:27
|
||||
*/
|
||||
public interface IWxMsgPushService {
|
||||
|
||||
/**
|
||||
* 创建一个带参数的二维码,用户扫码的时候,回调里面会携带二维码的参数.
|
||||
*
|
||||
* @return 二维码
|
||||
*/
|
||||
String getOrCode();
|
||||
|
||||
}
|
||||
@ -0,0 +1,75 @@
|
||||
package top.baogutang.business.services.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.zjiecode.wxpusher.client.WxPusher;
|
||||
import com.zjiecode.wxpusher.client.bean.CreateQrcodeReq;
|
||||
import com.zjiecode.wxpusher.client.bean.CreateQrcodeResp;
|
||||
import com.zjiecode.wxpusher.client.bean.Result;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.baogutang.business.services.IWxMsgPushService;
|
||||
import top.baogutang.common.constants.ErrorCodeEnum;
|
||||
import top.baogutang.common.exceptions.BusinessException;
|
||||
import top.baogutang.common.properties.WxMsgPushProperties;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static top.baogutang.common.constants.CacheConstant.WX_MSG_PUSH_QR_CODE_PREFIX;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/16 : 10:27
|
||||
*/
|
||||
@Slf4j
|
||||
@RefreshScope
|
||||
@Service
|
||||
public class WxMsgPushServiceImpl implements IWxMsgPushService {
|
||||
|
||||
/**
|
||||
* 二维码有效时间
|
||||
*/
|
||||
private static final Integer QR_CODE_EXPIRE_TIME = 10 * 24 * 60 * 60;
|
||||
|
||||
@Resource
|
||||
private WxMsgPushProperties wxMsgPushProperties;
|
||||
|
||||
@Resource
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
@Override
|
||||
public String getOrCode() {
|
||||
String cacheKey = String.format(WX_MSG_PUSH_QR_CODE_PREFIX, wxMsgPushProperties.getAppToken());
|
||||
Object cacheUrlObj = redisTemplate.opsForValue().get(cacheKey);
|
||||
if (Objects.nonNull(cacheUrlObj)) {
|
||||
return (String) cacheUrlObj;
|
||||
}
|
||||
CreateQrcodeReq createQrcodeReq = new CreateQrcodeReq();
|
||||
//必填,应用的appToken
|
||||
createQrcodeReq.setAppToken(wxMsgPushProperties.getAppToken());
|
||||
//必填,携带的参数
|
||||
createQrcodeReq.setExtra("Niko's MP");
|
||||
//可选,二维码有效时间,默认1800 s,最大30天,单位是s
|
||||
createQrcodeReq.setValidTime(QR_CODE_EXPIRE_TIME);
|
||||
Result<CreateQrcodeResp> respResult = null;
|
||||
try {
|
||||
respResult = WxPusher.createAppTempQrcode(createQrcodeReq);
|
||||
} catch (Exception e) {
|
||||
log.error(">>>>>>>>>>创建二维码异常:{}<<<<<<<<<<", e.getMessage(), e);
|
||||
throw new BusinessException(ErrorCodeEnum.E_BIZ_ERROR);
|
||||
}
|
||||
log.info(">>>>>>>>>>创建临时二维码请求参数:{},响应参数:{}<<<<<<<<<<", JSON.toJSONString(createQrcodeReq), JSON.toJSONString(respResult));
|
||||
if (respResult.isSuccess()) {
|
||||
//创建成功
|
||||
CreateQrcodeResp createQrcodeResp = respResult.getData();
|
||||
redisTemplate.opsForValue().set(cacheKey, createQrcodeResp.getUrl(), QR_CODE_EXPIRE_TIME, TimeUnit.SECONDS);
|
||||
return createQrcodeResp.getUrl();
|
||||
}
|
||||
throw new BusinessException(ErrorCodeEnum.E_BIZ_ERROR);
|
||||
}
|
||||
}
|
||||
19
baogutang-business/src/main/resources/bootstrap-local.yml
Normal file
19
baogutang-business/src/main/resources/bootstrap-local.yml
Normal file
@ -0,0 +1,19 @@
|
||||
spring:
|
||||
application:
|
||||
name: baogutang-business
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
server-addr: 42.51.4.235:8848
|
||||
config:
|
||||
server-addr: 42.51.4.235:8848
|
||||
namespace: adcc486c-d6fb-465a-a4f6-3fea7234433b
|
||||
file-extension: yml
|
||||
refresh-enabled: true
|
||||
group: DEFAULT_GROUP
|
||||
username: nacos
|
||||
password: 199312
|
||||
# shared-configs:
|
||||
# - data-id: goods-blindbox.yml
|
||||
# refresh: true
|
||||
|
||||
19
baogutang-business/src/main/resources/bootstrap-prod.yml
Normal file
19
baogutang-business/src/main/resources/bootstrap-prod.yml
Normal file
@ -0,0 +1,19 @@
|
||||
spring:
|
||||
application:
|
||||
name: baogutang-business
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
server-addr: 42.51.4.235:8848
|
||||
config:
|
||||
server-addr: 42.51.4.235:8848
|
||||
namespace: 50b370f0-6fc9-4e1d-9a19-df276cff9eac
|
||||
file-extension: yml
|
||||
refresh-enabled: true
|
||||
group: DEFAULT_GROUP
|
||||
username: nacos
|
||||
password: 199312
|
||||
# shared-configs:
|
||||
# - data-id: goods-blindbox.yml
|
||||
# refresh: true
|
||||
|
||||
19
baogutang-business/src/main/resources/bootstrap-test.yml
Normal file
19
baogutang-business/src/main/resources/bootstrap-test.yml
Normal file
@ -0,0 +1,19 @@
|
||||
spring:
|
||||
application:
|
||||
name: baogutang-business
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
server-addr: 42.51.4.235:8848
|
||||
config:
|
||||
server-addr: 42.51.4.235:8848
|
||||
namespace: 7e44b734-781d-4c21-a524-4bad1557d95f
|
||||
file-extension: yml
|
||||
refresh-enabled: true
|
||||
group: DEFAULT_GROUP
|
||||
username: nacos
|
||||
password: 199312
|
||||
# shared-configs:
|
||||
# - data-id: goods-blindbox.yml
|
||||
# refresh: true
|
||||
|
||||
5
baogutang-business/src/main/resources/bootstrap.yml
Normal file
5
baogutang-business/src/main/resources/bootstrap.yml
Normal file
@ -0,0 +1,5 @@
|
||||
spring:
|
||||
profiles:
|
||||
active: @profileActive@
|
||||
main:
|
||||
allow-bean-definition-overriding: true
|
||||
114
baogutang-business/src/main/resources/logback-spring.xml
Normal file
114
baogutang-business/src/main/resources/logback-spring.xml
Normal file
@ -0,0 +1,114 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration debug="false" scan="true" scanPeriod="1 seconds">
|
||||
<include resource="logback-default.xml"/>
|
||||
<contextName>logback</contextName>
|
||||
<springProperty scope="context" name="logStore" source="spring.application.name"/>
|
||||
<property name="log.path" value="/var/logs/${logStore}"/>
|
||||
|
||||
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} [%X{X-Request-Id}] [%thread] %-5level %logger - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${log.path}/app.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>${log.path}/%d{yyyy-MM-dd,aux}/app-%d{yyyy-MM-dd}.%i.log
|
||||
</fileNamePattern>
|
||||
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
|
||||
<maxFileSize>50MB</maxFileSize>
|
||||
</timeBasedFileNamingAndTriggeringPolicy>
|
||||
<!-- 保留最近60天的日志 -->
|
||||
<maxHistory>60</maxHistory>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%date{HH:mm:ss.SSS} [%X{X-Request-Id}] [%thread] %-5level %logger - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="asyncFileAppender" class="ch.qos.logback.classic.AsyncAppender">
|
||||
<queueSize>10000</queueSize>
|
||||
<discardingThreshold>0</discardingThreshold>
|
||||
<appender-ref ref="file"/>
|
||||
</appender>
|
||||
|
||||
<!-- 读取配置文件信息(交由各项目指定) -->
|
||||
<property name="active" value="${spring.profiles.active:-test}" />
|
||||
<property name="active" value="${env:-test}" />
|
||||
<springProperty scope="context" name="springEnv" source="spring.profiles.active" defaultValue="${active:-test}" />
|
||||
<springProperty scope="context" name="appEnv" source="server.application.logEnv" defaultValue="${springEnv:-test}" />
|
||||
<springProperty scope="context" name="appId" source="spring.application.name" defaultValue="localhost" />
|
||||
|
||||
<!--为了防止进程退出时,内存中的数据丢失,请加上此选项-->
|
||||
<shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook"/>
|
||||
|
||||
<!-- 外网 -->
|
||||
<appender name="ONLINE-OUT" class="com.aliyun.openservices.log.logback.LoghubAppender">
|
||||
<!--必选项 -->
|
||||
<endpoint>cn-shanghai.log.aliyuncs.com</endpoint>
|
||||
<accessKeyId>LTAI5tRN9T5Tz1QExcSpUaBc</accessKeyId>
|
||||
<accessKey>LniIMK15XEOc6Nn5mOrtX399FkVfQd</accessKey>
|
||||
<projectName>baogutang</projectName>
|
||||
<logstore>${appEnv}</logstore>
|
||||
|
||||
<!-- 可选项 -->
|
||||
<topic>${appId}</topic>
|
||||
<!-- <source>source1</source> -->
|
||||
|
||||
<!-- 可选项 详见 '参数说明' -->
|
||||
<packageTimeoutInMS>3000</packageTimeoutInMS>
|
||||
<logsCountPerPackage>4096</logsCountPerPackage>
|
||||
<logsBytesPerPackage>3145728</logsBytesPerPackage>
|
||||
<memPoolSizeInByte>104857600</memPoolSizeInByte>
|
||||
<retryTimes>3</retryTimes>
|
||||
<maxIOThreadSizeInPool>8</maxIOThreadSizeInPool>
|
||||
|
||||
<!-- 可选项 设置时区 -->
|
||||
<timeZone>Asia/Shanghai</timeZone>
|
||||
<!-- 可选项 设置时间格式 -->
|
||||
<timeFormat>yyyy-MM-dd HH:mm:ss.SSS</timeFormat>
|
||||
<!-- 可选项 通过配置 encoder 的 pattern 自定义 log 的格式 -->
|
||||
<encoder>
|
||||
<!-- <pattern>[${appId}] %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{0}: %msg</pattern> -->
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%X{X-Request-Id}] [%thread] %logger{0}: %msg</pattern>
|
||||
</encoder>
|
||||
|
||||
<!-- 指定级别的日志(INFO,WARN,ERROR) -->
|
||||
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
|
||||
<level>INFO</level>
|
||||
</filter>
|
||||
</appender>
|
||||
|
||||
<logger name="org.hibernate" level="ERROR" />
|
||||
<logger name="org.apache" level="ERROR" />
|
||||
<logger name="ch.qos.logback" level="WARN" />
|
||||
<logger name="org.elasticsearch" level="ERROR" />
|
||||
<logger name="org.mongodb.driver" level="INFO" />
|
||||
<logger name="springfox.documentation" level="WARN" />
|
||||
<logger name="com.aliyun.openservices.log" level="INFO" />
|
||||
<logger name="com" level="INFO"/>
|
||||
<logger name="top" level="INFO"/>
|
||||
<logger name="net" level="ERROR"/>
|
||||
<logger name="org" level="INFO"/>
|
||||
<logger name="io" level="INFO"/>
|
||||
<logger name="springfox" level="INFO"/>
|
||||
<logger name="Validator" level="INFO"/>
|
||||
<logger name="org.springframework" level="INFO"/>
|
||||
|
||||
|
||||
<springProfile name="test,prod">
|
||||
<root level="DEBUG">
|
||||
<appender-ref ref="console"/>
|
||||
<appender-ref ref="ONLINE-OUT"/>
|
||||
</root>
|
||||
</springProfile>
|
||||
|
||||
<springProfile name="local">
|
||||
<root level="DEBUG">
|
||||
<appender-ref ref="console"/>
|
||||
<appender-ref ref="ONLINE-OUT"/>
|
||||
</root>
|
||||
</springProfile>
|
||||
|
||||
</configuration>
|
||||
139
baogutang-common/pom.xml
Normal file
139
baogutang-common/pom.xml
Normal file
@ -0,0 +1,139 @@
|
||||
<?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>top.baogutang</groupId>
|
||||
<artifactId>baogutang-parent</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>baogutang-common</artifactId>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-aop</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-integration</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-context</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.integration</groupId>
|
||||
<artifactId>spring-integration-redis</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-pool2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-lang</groupId>
|
||||
<artifactId>commons-lang</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-annotations</artifactId>
|
||||
<version>1.5.22</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun.openservices</groupId>
|
||||
<artifactId>ons-client</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-green</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun.oss</groupId>
|
||||
<artifactId>aliyun-sdk-oss</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>tea-openapi</artifactId>
|
||||
<version>0.2.2</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
|
||||
<dependency>
|
||||
<groupId>io.searchbox</groupId>
|
||||
<artifactId>jest</artifactId>
|
||||
<version>6.3.1</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/io.searchbox/jest-common -->
|
||||
<dependency>
|
||||
<groupId>io.searchbox</groupId>
|
||||
<artifactId>jest-common</artifactId>
|
||||
<version>6.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zjiecode</groupId>
|
||||
<artifactId>wxpusher-java-sdk</artifactId>
|
||||
<version>2.1.4</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@ -0,0 +1,20 @@
|
||||
package top.baogutang.common.annotation;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 11:31
|
||||
*/
|
||||
@Documented
|
||||
@Target({ElementType.TYPE, ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface LoginRequired {
|
||||
|
||||
boolean required() default true;
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
package top.baogutang.common.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:04
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface RequestLimit {
|
||||
|
||||
/**
|
||||
* 指定时间内不可重复提交,单位秒
|
||||
*/
|
||||
long timeout() default 1;
|
||||
|
||||
/**
|
||||
* 时间单位
|
||||
*/
|
||||
TimeUnit timeUnit() default TimeUnit.SECONDS;
|
||||
|
||||
/**
|
||||
* 指定key
|
||||
*/
|
||||
String key() default "";
|
||||
|
||||
/**
|
||||
* 是否限制单个人的, 包含token
|
||||
*/
|
||||
boolean includeToken() default true;
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
package top.baogutang.common.annotation;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:07
|
||||
*/
|
||||
@Documented
|
||||
@Target({ElementType.TYPE, ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface VerifyRequired {
|
||||
}
|
||||
@ -0,0 +1,65 @@
|
||||
package top.baogutang.common.aspect;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.serializer.SerializerFeature;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestAttributes;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import top.baogutang.common.domain.Results;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:16
|
||||
*/
|
||||
@Slf4j
|
||||
@Aspect
|
||||
@Component
|
||||
public class LogAspect {
|
||||
|
||||
|
||||
@Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
|
||||
public void logPointCut() {
|
||||
//pointCut
|
||||
|
||||
}
|
||||
|
||||
@Around("logPointCut()")
|
||||
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
|
||||
Object result;
|
||||
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
|
||||
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
|
||||
assert sra != null;
|
||||
HttpServletRequest request = sra.getRequest();
|
||||
String requestId = MDC.get("X-Request-Id");
|
||||
long startMills = System.currentTimeMillis();
|
||||
long cost = 0;
|
||||
try {
|
||||
result = pjp.proceed();
|
||||
cost = System.currentTimeMillis() - startMills;
|
||||
log.info("请求结束!本次请求耗时:{},url: {}, method: {}, params: {},user:{}, token: {}, 响应结果:{}",
|
||||
cost, request.getRequestURL().toString(),
|
||||
request.getMethod(), pjp.getArgs(), JSON.toJSONString(request.getAttribute("user")), request.getHeader("authorization"),
|
||||
JSON.toJSONString(result, SerializerFeature.DisableCircularReferenceDetect));
|
||||
if (result instanceof Results) {
|
||||
Results r = (Results) result;
|
||||
r.setRid(requestId);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("请求异常!!!本次请求耗时:{},error:{},url: {}, method: {}, params: {},user:{}, token: {}", cost, e, request.getRequestURL().toString(),
|
||||
request.getMethod(), pjp.getArgs(), JSON.toJSONString(request.getAttribute("user")), request.getHeader("token"));
|
||||
throw e;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,115 @@
|
||||
package top.baogutang.common.aspect;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.aspectj.lang.annotation.After;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import top.baogutang.common.annotation.LoginRequired;
|
||||
import top.baogutang.common.components.TokenComponent;
|
||||
import top.baogutang.common.constants.CacheConstant;
|
||||
import top.baogutang.common.domain.JwtBody;
|
||||
import top.baogutang.common.domain.TokenCodeEnum;
|
||||
import top.baogutang.common.exceptions.BusinessException;
|
||||
import top.baogutang.common.utils.UserThreadLocal;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Objects;
|
||||
|
||||
import static top.baogutang.common.constants.JwtConstant.AUTHORIZATION;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 11:32
|
||||
*/
|
||||
@Slf4j
|
||||
@Aspect
|
||||
@Component
|
||||
public class LoginRequiredAspect {
|
||||
|
||||
@Resource
|
||||
private TokenComponent tokenComponent;
|
||||
|
||||
@Resource
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
@Pointcut("@annotation(top.baogutang.common.annotation.LoginRequired)")
|
||||
public void point() {
|
||||
}
|
||||
|
||||
@Before(value = "point() && @annotation(loginRequired)")
|
||||
public void verifyTokenForClass(LoginRequired loginRequired) {
|
||||
if (loginRequired.required()) {
|
||||
checkToken();
|
||||
} else {
|
||||
checkTokenWithOutRequired();
|
||||
}
|
||||
}
|
||||
|
||||
@After("point()")
|
||||
public void after() {
|
||||
UserThreadLocal.remove();
|
||||
}
|
||||
|
||||
private void checkToken() {
|
||||
|
||||
ServletRequestAttributes requestAttributes =
|
||||
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
if (Objects.isNull(requestAttributes)) {
|
||||
return;
|
||||
}
|
||||
HttpServletRequest request = requestAttributes.getRequest();
|
||||
String token = request.getHeader(AUTHORIZATION);
|
||||
if (StringUtils.isEmpty(token)) {
|
||||
throw new BusinessException(
|
||||
TokenCodeEnum.AUTH_TOKEN_EMPTY.getCode(), TokenCodeEnum.AUTH_TOKEN_EMPTY.getMessage());
|
||||
}
|
||||
|
||||
log.info("request url:{},method:{}", request.getRequestURL(), request.getMethod());
|
||||
JwtBody body = tokenComponent.parseToken(token);
|
||||
Long userId = body.getId();
|
||||
Object val = redisTemplate.opsForValue().get(CacheConstant.TOKEN + userId);
|
||||
if (Objects.isNull(val)) {
|
||||
redisTemplate.opsForValue().set(CacheConstant.TOKEN + userId, token);
|
||||
} else {
|
||||
//比对token、不相同则判断token生产时间,取最新的覆盖
|
||||
String redisToken = String.valueOf(val);
|
||||
if (!token.equals(redisToken)) {
|
||||
JwtBody redisBody = tokenComponent.parseToken(redisToken);
|
||||
if (body.getIat() > redisBody.getIat()) {
|
||||
log.info("newTokenCover,currentBody:{} redisBody:{}", JSON.toJSONString(body), JSON.toJSONString(redisBody));
|
||||
redisTemplate.opsForValue().set(CacheConstant.TOKEN + userId, token);
|
||||
} else {
|
||||
log.info("FoundOldToken,currentBody:{} redisBody:{}", JSON.toJSONString(body), JSON.toJSONString(redisBody));
|
||||
throw new BusinessException(
|
||||
TokenCodeEnum.AUTH_FAILED.getCode(), TokenCodeEnum.AUTH_FAILED.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
UserThreadLocal.set(body.getId());
|
||||
}
|
||||
|
||||
private void checkTokenWithOutRequired() {
|
||||
ServletRequestAttributes requestAttributes =
|
||||
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
if (Objects.isNull(requestAttributes)) {
|
||||
return;
|
||||
}
|
||||
HttpServletRequest request = requestAttributes.getRequest();
|
||||
String token = request.getHeader(AUTHORIZATION);
|
||||
if (StringUtils.isNotEmpty(token)) {
|
||||
log.info("request url:{},method:{}", request.getRequestURL(), request.getMethod());
|
||||
JwtBody body = tokenComponent.parseToken(token);
|
||||
UserThreadLocal.set(body.getId());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,127 @@
|
||||
package top.baogutang.common.aspect;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import top.baogutang.common.annotation.RequestLimit;
|
||||
import top.baogutang.common.domain.Results;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:05
|
||||
*/
|
||||
@Slf4j
|
||||
@Aspect
|
||||
@Component
|
||||
public class RequestLimitAspect {
|
||||
|
||||
|
||||
@Resource
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
@Pointcut("@annotation(top.baogutang.common.annotation.RequestLimit)")
|
||||
public void limit() {
|
||||
}
|
||||
|
||||
@Around("limit()")
|
||||
public Object around(ProceedingJoinPoint point) throws Throwable {
|
||||
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
|
||||
String ip = getIpAddress(request);
|
||||
MethodSignature signature = (MethodSignature) point.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
RequestLimit requestLimit = method.getAnnotation(RequestLimit.class);
|
||||
if (requestLimit != null) {
|
||||
String key = requestLimit.key();
|
||||
if (StringUtils.isEmpty(key)) {
|
||||
String className = method.getDeclaringClass().getName();
|
||||
String name = method.getName();
|
||||
String args = Arrays.toString(point.getArgs());
|
||||
String ipKey = String.format("%s#%s#%s", className, name, args);
|
||||
int hashCode = Math.abs(ipKey.hashCode());
|
||||
key = String.format("%s_%d", ip, hashCode);
|
||||
}
|
||||
if (requestLimit.includeToken()) {
|
||||
String token = request.getHeader("authorization");
|
||||
if (token != null) {
|
||||
key = key.concat("_").concat(DigestUtils.md5Hex(token));
|
||||
}
|
||||
}
|
||||
long timeout = requestLimit.timeout();
|
||||
TimeUnit timeUnit = requestLimit.timeUnit();
|
||||
if (timeout < 0) {
|
||||
//过期时间5s
|
||||
timeout = 5;
|
||||
}
|
||||
Boolean lock = redisTemplate.opsForValue().setIfAbsent(key, "1", timeout, timeUnit);
|
||||
if (!Boolean.TRUE.equals(lock)) {
|
||||
return Results.failed("正在赶来中,请稍后再试~");
|
||||
}
|
||||
}
|
||||
return point.proceed();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取请求用户的IP地址
|
||||
*
|
||||
* @param request request
|
||||
* @return return
|
||||
*/
|
||||
public String getIpAddress(HttpServletRequest request) {
|
||||
|
||||
String ipAddresses = request.getHeader("x-forwarded-for");
|
||||
|
||||
ipAddresses = getString(request, ipAddresses);
|
||||
|
||||
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
|
||||
//X-Real-IP:nginx服务代理
|
||||
ipAddresses = request.getHeader("X-Real-IP");
|
||||
}
|
||||
|
||||
//有些网络通过多层代理,那么获取到的ip就会有多个,一般都是通过逗号(,)分割开来,并且第一个ip为客户端的真实IP
|
||||
if (ipAddresses != null && ipAddresses.length() != 0) {
|
||||
ipAddresses = ipAddresses.split(",")[0];
|
||||
}
|
||||
|
||||
//还是不能获取到,最后再通过request.getRemoteAddr();获取
|
||||
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
|
||||
ipAddresses = request.getRemoteAddr();
|
||||
}
|
||||
|
||||
return ipAddresses;
|
||||
}
|
||||
|
||||
public static String getString(HttpServletRequest request, String ipAddresses) {
|
||||
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
|
||||
//Proxy-Client-IP:apache 服务代理
|
||||
ipAddresses = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
|
||||
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
|
||||
//WL-Proxy-Client-IP:weblogic 服务代理
|
||||
ipAddresses = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
|
||||
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
|
||||
//HTTP_CLIENT_IP:有些代理服务器
|
||||
ipAddresses = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
return ipAddresses;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,100 @@
|
||||
package top.baogutang.common.aspect;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.After;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import top.baogutang.common.annotation.VerifyRequired;
|
||||
import top.baogutang.common.components.TokenComponent;
|
||||
import top.baogutang.common.constants.CacheConstant;
|
||||
import top.baogutang.common.domain.JwtBody;
|
||||
import top.baogutang.common.domain.Results;
|
||||
import top.baogutang.common.domain.TokenCodeEnum;
|
||||
import top.baogutang.common.exceptions.BusinessException;
|
||||
import top.baogutang.common.utils.UserThreadLocal;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Objects;
|
||||
|
||||
import static top.baogutang.common.constants.ErrorCodeEnum.E_BIZ_NEED_VERIFY;
|
||||
import static top.baogutang.common.constants.JwtConstant.AUTHORIZATION;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:07
|
||||
*/
|
||||
@Slf4j
|
||||
@Aspect
|
||||
@Component
|
||||
public class VerifyRequiredAspect {
|
||||
|
||||
|
||||
@Resource
|
||||
private TokenComponent tokenComponent;
|
||||
|
||||
@Resource
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
@Pointcut("@annotation(top.baogutang.common.annotation.VerifyRequired)")
|
||||
public void verify() {
|
||||
}
|
||||
|
||||
@Around("verify()")
|
||||
public Object around(ProceedingJoinPoint point) throws Throwable {
|
||||
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
|
||||
MethodSignature signature = (MethodSignature) point.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
VerifyRequired verifyRequired = method.getAnnotation(VerifyRequired.class);
|
||||
if (verifyRequired != null) {
|
||||
String token = request.getHeader(AUTHORIZATION);
|
||||
if (StringUtils.isBlank(token)) {
|
||||
throw new BusinessException(
|
||||
TokenCodeEnum.AUTH_TOKEN_EMPTY.getCode(), TokenCodeEnum.AUTH_TOKEN_EMPTY.getMessage());
|
||||
}
|
||||
JwtBody body = tokenComponent.parseToken(token);
|
||||
Long userId = body.getId();
|
||||
UserThreadLocal.set(userId);
|
||||
if (Objects.isNull(redisTemplate.opsForValue().get(CacheConstant.USER_VERIFY_KEY_PREFIX + userId))) {
|
||||
return Results.failed(E_BIZ_NEED_VERIFY.getCode(), E_BIZ_NEED_VERIFY.getMsg());
|
||||
}
|
||||
Object val = redisTemplate.opsForValue().get(CacheConstant.TOKEN + userId);
|
||||
if (Objects.isNull(val)) {
|
||||
redisTemplate.opsForValue().set(CacheConstant.TOKEN + userId, token);
|
||||
} else {
|
||||
//比对token、不相同则判断token生产时间,取最新的覆盖
|
||||
String redisToken = String.valueOf(val);
|
||||
if (!token.equals(redisToken)) {
|
||||
JwtBody redisBody = tokenComponent.parseToken(redisToken);
|
||||
if (body.getIat() > redisBody.getIat()) {
|
||||
log.info("VerifyNewTokenCover,currentBody:{} redisBody:{}", JSON.toJSONString(body), JSON.toJSONString(redisBody));
|
||||
redisTemplate.opsForValue().set(CacheConstant.TOKEN + userId, token);
|
||||
} else {
|
||||
log.info("FoundOldToken,currentBody:{} redisBody:{}", JSON.toJSONString(body), JSON.toJSONString(redisBody));
|
||||
throw new BusinessException(
|
||||
TokenCodeEnum.AUTH_FAILED.getCode(), TokenCodeEnum.AUTH_FAILED.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return point.proceed();
|
||||
}
|
||||
|
||||
@After("verify()")
|
||||
public void after() {
|
||||
UserThreadLocal.remove();
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,109 @@
|
||||
package top.baogutang.common.components;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.ExpiredJwtException;
|
||||
import io.jsonwebtoken.Jws;
|
||||
import io.jsonwebtoken.JwtBuilder;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.Base64Utils;
|
||||
import top.baogutang.common.domain.JwtBody;
|
||||
import top.baogutang.common.domain.TokenCodeEnum;
|
||||
import top.baogutang.common.exceptions.BusinessException;
|
||||
|
||||
import java.security.KeyFactory;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static top.baogutang.common.constants.JwtConstant.ALGORITHM_FAMILY_NAME;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 11:45
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class TokenComponent {
|
||||
@Value("${jwt.publicKey:1}")
|
||||
private String publicKey;
|
||||
|
||||
public JwtBody parseToken(String token) {
|
||||
log.info("parse token:{}", token);
|
||||
Jws<Claims> claimsJws;
|
||||
try {
|
||||
claimsJws = Jwts.parser().setSigningKey(publicKeyFromBase64()).parseClaimsJws(token);
|
||||
} catch (ExpiredJwtException expiredJwtException) {
|
||||
return new JwtBody(expiredJwtException.getClaims());
|
||||
|
||||
} catch (JwtException e) {
|
||||
if (e.getMessage().contains("expired")) {
|
||||
throw new BusinessException(
|
||||
TokenCodeEnum.AUTH_TIME_OUT.getCode(), TokenCodeEnum.AUTH_TIME_OUT.getMessage());
|
||||
}
|
||||
throw new BusinessException(
|
||||
TokenCodeEnum.AUTH_FAILED.getCode(), TokenCodeEnum.AUTH_FAILED.getMessage());
|
||||
}
|
||||
return new JwtBody(claimsJws.getBody());
|
||||
}
|
||||
|
||||
public static String createToken(String data, long secondTime, String subject) {
|
||||
JwtBuilder jwtBuilder = Jwts.builder();
|
||||
subject = subject != null ? subject : UUID.randomUUID().toString();
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
if (StringUtils.isNotEmpty(data)) {
|
||||
map.put("data", data);
|
||||
}
|
||||
jwtBuilder.setClaims(map).setSubject(subject);
|
||||
long currentTime = System.currentTimeMillis();
|
||||
if (secondTime == 0) {
|
||||
currentTime += 30 * 60 * 1000;
|
||||
} else {
|
||||
currentTime += secondTime * 1000;
|
||||
}
|
||||
Date newDate = new Date(currentTime);
|
||||
jwtBuilder.setExpiration(newDate);
|
||||
return jwtBuilder.signWith(SignatureAlgorithm.ES256, privateKeyFromBase64()).compact();
|
||||
}
|
||||
|
||||
private static PrivateKey privateKeyFromBase64() {
|
||||
try {
|
||||
byte[] keyBytes = Base64Utils.decodeFromString("MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgn9N3dA834ctlm7jkBXcRvR4+/hnYjZvYO1s5hisWG0yhRANCAAR91zvPpA/9Mc4DtxAWwWsnhj1rGk0XmTNqdnfPQJmLazYXaUvEuYuR+SNf6pl0OH2jLoAsXUFYtIFUzV/qv9ph");
|
||||
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
|
||||
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_FAMILY_NAME);
|
||||
return keyFactory.generatePrivate(keySpec);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 公钥64位序列化
|
||||
*
|
||||
* @return PublicKey
|
||||
*/
|
||||
private PublicKey publicKeyFromBase64() {
|
||||
try {
|
||||
byte[] keyBytes = Base64Utils.decodeFromString(publicKey);
|
||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
|
||||
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_FAMILY_NAME);
|
||||
return keyFactory.generatePublic(keySpec);
|
||||
} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
|
||||
throw new IllegalArgumentException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
package top.baogutang.common.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
|
||||
/**
|
||||
* @description: 线程池配置
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:18
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
public class ExecutorConfig {
|
||||
|
||||
@Value("${spring.application.name}")
|
||||
private String appName;
|
||||
|
||||
@Value("${thread.pool.core.pool.size:10}")
|
||||
private Integer corePoolSize;
|
||||
|
||||
@Value("${thread.pool.max.pool.size:20}")
|
||||
private Integer maxPoolSize;
|
||||
|
||||
@Value("${thread.pool.keep.alive.second:10}")
|
||||
private Integer keepAliveSecond;
|
||||
|
||||
@Value("${thread.pool.queue.capacity:200}")
|
||||
private Integer queueCapacity;
|
||||
|
||||
@Bean("commonExecutor")
|
||||
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setThreadNamePrefix(appName);
|
||||
executor.setCorePoolSize(corePoolSize);
|
||||
executor.setMaxPoolSize(maxPoolSize);
|
||||
executor.setKeepAliveSeconds(keepAliveSecond);
|
||||
executor.setQueueCapacity(queueCapacity);
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
executor.setWaitForTasksToCompleteOnShutdown(true);
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
package top.baogutang.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* @description: 全局跨域配置
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:19
|
||||
*/
|
||||
@Configuration
|
||||
public class GlobalCorsConfig {
|
||||
|
||||
@Bean
|
||||
public WebMvcConfigurer corsConfigurer() {
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
//重写父类提供的跨域请求处理的接口
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
//添加映射路径
|
||||
registry.addMapping("/**")
|
||||
//放行哪些原始域
|
||||
.allowedOrigins("*")
|
||||
//是否发送Cookie信息
|
||||
.allowCredentials(true)
|
||||
//放行哪些原始域(请求方式)
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||
//放行哪些原始域(头部信息)
|
||||
.allowedHeaders("*")
|
||||
//暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
|
||||
.exposedHeaders("Header1", "Header2");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,45 @@
|
||||
package top.baogutang.common.config;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.task.TaskDecorator;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @description: 多线程链路ID
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:20
|
||||
*/
|
||||
@Configuration
|
||||
public class GlobalMDCTaskDecorator implements TaskDecorator, BeanPostProcessor {
|
||||
|
||||
|
||||
@Override
|
||||
public Runnable decorate(Runnable runnable) {
|
||||
Map<String, String> mdcContext = MDC.getCopyOfContextMap();
|
||||
return () -> {
|
||||
try {
|
||||
if (mdcContext != null) {
|
||||
MDC.setContextMap(mdcContext);
|
||||
}
|
||||
runnable.run();
|
||||
} finally {
|
||||
MDC.clear();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean instanceof ThreadPoolTaskExecutor) {
|
||||
((ThreadPoolTaskExecutor) bean).setTaskDecorator(this);
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,44 @@
|
||||
package top.baogutang.common.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:25
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@Order(1)
|
||||
public class MdcRequestIdFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final String REQUEST_ID_KEY = "X-Request-Id";
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
||||
try {
|
||||
String traceId = request.getHeader(REQUEST_ID_KEY);
|
||||
if (traceId == null) {
|
||||
traceId = UUID.randomUUID().toString().replace("-", "");
|
||||
log.info("requestId为空,自动生成 {}", traceId);
|
||||
request.setAttribute(REQUEST_ID_KEY, traceId);
|
||||
}
|
||||
MDC.put(REQUEST_ID_KEY, traceId);
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
MDC.remove(REQUEST_ID_KEY);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
package top.baogutang.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: developer
|
||||
* @date: 2022/05/26 : 15:51
|
||||
*/
|
||||
@Configuration
|
||||
public class MybatisPlusConfig {
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
//分页插件
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
|
||||
//乐观锁插件
|
||||
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
|
||||
return interceptor;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,85 @@
|
||||
package top.baogutang.common.config;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
import org.springframework.integration.redis.util.RedisLockRegistry;
|
||||
import org.springframework.scripting.support.ResourceScriptSource;
|
||||
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
/**
|
||||
* @description: 缓存配置
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:21
|
||||
*/
|
||||
@Slf4j
|
||||
@EnableCaching
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
|
||||
|
||||
@Bean
|
||||
@SuppressWarnings("all")
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
|
||||
// 为了开发方便,直接使用<String, Object>
|
||||
RedisTemplate<String, Object> template = new RedisTemplate();
|
||||
template.setConnectionFactory(redisConnectionFactory);
|
||||
|
||||
// Json 配置序列化
|
||||
// 使用 jackson 解析任意的对象
|
||||
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
|
||||
// 使用 objectMapper 进行转义
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
|
||||
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
|
||||
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
|
||||
// String 的序列化
|
||||
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
|
||||
|
||||
// key 采用 String 的序列化方式
|
||||
template.setKeySerializer(stringRedisSerializer);
|
||||
// Hash 的 key 采用 String 的序列化方式
|
||||
template.setHashKeySerializer(stringRedisSerializer);
|
||||
// value 采用 jackson 的序列化方式
|
||||
template.setValueSerializer(jackson2JsonRedisSerializer);
|
||||
// Hash 的 value 采用 String 的序列化方式
|
||||
template.setHashValueSerializer(jackson2JsonRedisSerializer);
|
||||
// 把所有的配置 set 进 template
|
||||
template.afterPropertiesSet();
|
||||
|
||||
return template;
|
||||
}
|
||||
|
||||
@Bean(destroyMethod = "destroy")
|
||||
public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory) {
|
||||
return new RedisLockRegistry(redisConnectionFactory, "lock");
|
||||
}
|
||||
|
||||
@Bean("accquireRedisScript")
|
||||
public DefaultRedisScript<Boolean> accquireRedisScript() {
|
||||
DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>();
|
||||
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/accquire.lua")));
|
||||
redisScript.setResultType(Boolean.class);
|
||||
return redisScript;
|
||||
}
|
||||
|
||||
@Bean("ipLimitRedisScript")
|
||||
public DefaultRedisScript<Boolean> ipLimitRedisScript() {
|
||||
DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>();
|
||||
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/ipLimit.lua")));
|
||||
redisScript.setResultType(Boolean.class);
|
||||
return redisScript;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
package top.baogutang.common.constants;
|
||||
|
||||
/**
|
||||
* @description: 缓存常量
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 11:28
|
||||
*/
|
||||
public class CacheConstant {
|
||||
|
||||
/**
|
||||
* 实名认证完成
|
||||
*/
|
||||
public static final String USER_VERIFY_KEY_PREFIX = "top:baogutang:user:verify:";
|
||||
|
||||
public static final String TOKEN = "top:baogutang:user:token:";
|
||||
|
||||
/**
|
||||
* 微信消息推送获取临时二维码缓存key
|
||||
*/
|
||||
public static final String WX_MSG_PUSH_QR_CODE_PREFIX = "top:baogutang:wx:msg_push:%s:";
|
||||
}
|
||||
@ -0,0 +1,80 @@
|
||||
package top.baogutang.common.constants;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 11:48
|
||||
*/
|
||||
public enum ErrorCodeEnum {
|
||||
/**
|
||||
* 数据不存在
|
||||
*/
|
||||
E_BIZ_ERROR(80800000, "请稍后重试~"),
|
||||
E_BIZ_ALREADY_VERIFIED(81010001, "您已经完成认证了哦~"),
|
||||
E_BIZ_ID_NO_ALREADY_VERIFIED(81010002, "该身份证已被认证哦~"),
|
||||
E_PARAM_ID_NO_INCORRECT(81010003, "您输入的身份证有误哦~"),
|
||||
E_PARAM_MOBILE_INCORRECT(81010004, "您输入的手机号有误哦~"),
|
||||
E_PARAM_MSG_INCORRECT(81010005, "短信验证码不正确哟~"),
|
||||
E_BIZ_MSG_SEND_FAIL(81010006, "请求频繁哟~"),
|
||||
E_BIZ_NEED_VERIFY(81010007, "请完成实名认证~"),
|
||||
|
||||
E_BIZ_DIGITAL_ART_DELAY_ORDER_PROCESS_ERROR(81010015, "订单已超时哦~"),
|
||||
E_BIZ_DIGITAL_ART_CREATE_ORDER_ERROR(81010016, "创建订单失败"),
|
||||
E_BIZ_DIGITAL_ART_CREATE_PAYMENT_UPDATE_ORDER_ERROR(81010017, "创建支付数据更新订单失败"),
|
||||
E_BIZ_DIGITAL_ART_STORAGE_DATA_NOT_EXISTS(81010018, "库存不存在哦~"),
|
||||
E_BIZ_DIGITAL_ART_STORAGE_EXISTS_PENDING_ORDER(81010019, "当前库存存在进行中订单哦~"),
|
||||
E_BIZ_DIGITAL_ART_STORAGE_EXISTS_NICKNAME(81010020, "当前昵称已存在"),
|
||||
E_BIZ_DIGITAL_ART_ORDER_NOT_EXISTS(81010022, "订单不存在哦~"),
|
||||
E_BIZ_DIGITAL_ART_ORDER_ALREADY_PAID(81010023, "订单已支付哦~"),
|
||||
E_BIZ_DIGITAL_ART_ACCOUNT_NOT_EXISTS(81010015, "账户信息不存在,请先绑定支付宝~"),
|
||||
E_BIZ_DIGITAL_ART_ACCOUNT_STATE_ERROR(81010016, "账户状态异常,请联系官方~"),
|
||||
E_BIZ_DIGITAL_ART_USER_NOT_EXISTS(81010017, "用户信息不存在哦~"),
|
||||
E_BIZ_DIGITAL_ART_MSG_CODE_NOT_EXISTS(81010018, "验证码已失效,请重新发送~"),
|
||||
E_BIZ_DIGITAL_ART_MSG_CODE_NOT_VALID(81010019, "验证码错误,请重新输入~"),
|
||||
E_BIZ_DIGITAL_ART_MOBILE_EMAIL_NOT_AVAILABLE(81010020, "仅能填写手机号或邮箱哦~"),
|
||||
E_BIZ_DIGITAL_ART_PASSWORD_NOT_VALID(81010022, "支付密码只能是数字哦~"),
|
||||
E_BIZ_DIGITAL_ART_PAY_PASSWORD_NOT_SET(81010023, "支付密码还未设置哦~"),
|
||||
E_BIZ_DIGITAL_ART_PAY_PASSWORD_FAIL(81010024, "支付密码错误,请重新输入~"),
|
||||
E_BIZ_DIGITAL_ART_PAY_PASSWORD_FAILS(81010025, "输入错误次数过多,请稍后再试~"),
|
||||
E_BIZ_DIGITAL_ART_PAY_ACCOUNT_NOT_BOUND(81010026, "请先绑定支付宝~"),
|
||||
E_BIZ_DIGITAL_ART_ACCOUNT_BALANCE_NOT_ENOUGH(81010027, "账户余额不足~"),
|
||||
E_BIZ_DIGITAL_ART_CASH_TOO_MANY_TIMES(81010028, "超过最大提现次数,请明天再来~"),
|
||||
E_BIZ_DIGITAL_ART_CASH_TOO_MANY_AMOUNT(81010029, "当日累计提现已超过最大提现金额~"),
|
||||
E_BIZ_DIGITAL_ART_CASH_ERROR(81010030, "提现失败,请稍后重试~"),
|
||||
E_BIZ_DIGITAL_ART_TRANS_ERROR(81010031, "交易失败,请稍后重试~"),
|
||||
E_BIZ_DIGITAL_ART_PASSWORD_LENGTH_NOT_VALID(81010033, "请输入六位支付密码~"),
|
||||
E_BIZ_DIGITAL_ART_EXCHANGE_MALL_OUT_OF_STOCK(81010040, "好遗憾,抢光了"),
|
||||
E_BIZ_DIGITAL_ART_GOODS_NOT_ENOUGH_STORAGE(81010048, "库存不足,请稍后重试~"),
|
||||
E_BIZ_DIGITAL_ART_VOUCHER_NOT_EXISTS(81010050, "兑换码不存在~"),
|
||||
E_BIZ_DIGITAL_ART_VOUCHER_ALREADY_USED(81010051, "兑换码已兑换~"),
|
||||
E_BIZ_DIGITAL_ART_VOUCHER_USER_HOLD_GOODS_NOT_ENOUGH(81010052, "暂无兑换资格"),
|
||||
E_BIZ_DIGITAL_ART_GOODS_LIMIT_BUY(81010053, "您已经达到购买上限"),
|
||||
|
||||
USER_NOT_EXITS(81010015, "用户不存在"),
|
||||
PASSWORD_ERROR(81010016, "密码错误"),
|
||||
NO_PERMISSION(81010017, "账号无权限"),
|
||||
E_BIZ_SIGN_ERROR(81011023, "签名错误~"),
|
||||
E_BIZ_NOT_COLLAB_GOODS_ERROR(81011024, "该商品不支持此操作~"),
|
||||
E_BIZ_MSG_SELL_LOCK(81011032, "请勿频繁操作~"),
|
||||
UNAUTHORIZED(401, "暂未登录或token已经过期"),
|
||||
FORBIDDEN(403, "没有相关权限"),
|
||||
AUTHORIZATION_HEADER_IS_EMPTY(600, "请求头中的token为空"),
|
||||
|
||||
DATA_IS_NULL(81011033, "数据为空");;
|
||||
|
||||
private final int code;
|
||||
private final String msg;
|
||||
|
||||
ErrorCodeEnum(int code, String msg) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
package top.baogutang.common.constants;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:02
|
||||
*/
|
||||
public class JwtConstant {
|
||||
|
||||
/**
|
||||
* token名称
|
||||
*/
|
||||
public static final String AUTHORIZATION = "authorization";
|
||||
|
||||
/**
|
||||
* 加密方式
|
||||
*/
|
||||
public static final String ALGORITHM_FAMILY_NAME = "EC";
|
||||
|
||||
}
|
||||
@ -0,0 +1,66 @@
|
||||
package top.baogutang.common.domain;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 11:47
|
||||
*/
|
||||
public class JwtBody {
|
||||
|
||||
private String subject;
|
||||
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 签发时间
|
||||
*/
|
||||
private Long iat;
|
||||
|
||||
public JwtBody(Claims claims) {
|
||||
if (Objects.nonNull(claims)) {
|
||||
this.subject = claims.getSubject();
|
||||
Map map = new HashMap<>(claims);
|
||||
this.iat = Long.valueOf(String.valueOf(map.get("iat")));
|
||||
this.id = Long.valueOf(String.valueOf(map.get("id")));
|
||||
}
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getIat() {
|
||||
return iat;
|
||||
}
|
||||
|
||||
public void setIat(Long iat) {
|
||||
this.iat = iat;
|
||||
}
|
||||
|
||||
public String getSubject() {
|
||||
return subject;
|
||||
}
|
||||
|
||||
public void setSubject(String subject) {
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JwtBody{" +
|
||||
"subject='" + subject + '\'' +
|
||||
", id=" + id +
|
||||
", iat=" + iat +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
package top.baogutang.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/16 : 12:28
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class Page<T> implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 7521438130006292396L;
|
||||
|
||||
private Integer totalCount;
|
||||
|
||||
private Integer pageSize;
|
||||
|
||||
private Integer totalPage;
|
||||
|
||||
private Integer currPage;
|
||||
|
||||
private List<T> list;
|
||||
}
|
||||
@ -0,0 +1,192 @@
|
||||
package top.baogutang.common.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import org.slf4j.MDC;
|
||||
import top.baogutang.common.constants.ErrorCodeEnum;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 11:54
|
||||
*/
|
||||
public class Results<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public static final int SUCCESS_CODE = 200;
|
||||
public static final int FAIL_CODE = 300;
|
||||
public static final String SUCCESS_MSG = "success";
|
||||
public static final int PARAM_ILLEGAL_CODE = 301;
|
||||
|
||||
@ApiModelProperty("响应码,200为请求成功;其他异常均为业务异常")
|
||||
private int code;
|
||||
@ApiModelProperty("响应信息")
|
||||
private String msg;
|
||||
@ApiModelProperty("业务数据")
|
||||
private T data;
|
||||
@ApiModelProperty("全局链路请求id")
|
||||
private String rid;
|
||||
|
||||
public Results() {
|
||||
}
|
||||
|
||||
public Results(int code, String msg) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public Results(int code, String msg, T data) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public static <T> Results<T> ok() {
|
||||
return restResult(null, 200, (String) null);
|
||||
}
|
||||
|
||||
public static <T> Results<T> ok(T data) {
|
||||
return restResult(data, SUCCESS_CODE, SUCCESS_MSG);
|
||||
}
|
||||
|
||||
public static <T> Results<T> ok(T data, int i, String msg) {
|
||||
return restResult(data, 200, (String) null);
|
||||
}
|
||||
|
||||
|
||||
public static <T> Results<T> ok(T data, String msg) {
|
||||
return restResult(data, 200, msg);
|
||||
}
|
||||
|
||||
public static <T> Results<T> result(T data, int code, String msg) {
|
||||
return restResult(data, code, msg);
|
||||
}
|
||||
|
||||
public static <T> Results<T> failed() {
|
||||
return restResult(null, 300, null);
|
||||
}
|
||||
|
||||
public static <T> Results<T> failed(String msg) {
|
||||
return restResult(null, 300, msg);
|
||||
}
|
||||
|
||||
public static <T> Results<T> failed(int code, String msg) {
|
||||
return restResult(null, code, msg);
|
||||
}
|
||||
|
||||
|
||||
public static <T> Results<T> failed(T data) {
|
||||
return restResult(data, 300, (String) null);
|
||||
}
|
||||
|
||||
public static <T> Results<T> failed(T data, String msg) {
|
||||
return restResult(data, 300, msg);
|
||||
}
|
||||
|
||||
public static <T> Results<T> restResult(T data, int code, String msg) {
|
||||
Results<T> r = new Results<>();
|
||||
r.setCode(code);
|
||||
r.setData(data);
|
||||
r.setMsg(msg);
|
||||
String rid = MDC.get("X-Request-Id");
|
||||
r.setRid(rid);
|
||||
return r;
|
||||
}
|
||||
|
||||
public static <T> Results<T> failed(ErrorCodeEnum errorCodeEnum) {
|
||||
return restResult(null, errorCodeEnum.getCode(), errorCodeEnum.getMsg());
|
||||
}
|
||||
|
||||
public Boolean isSuccess() {
|
||||
return this.code == SUCCESS_CODE;
|
||||
}
|
||||
|
||||
public static <T> boolean isSuccess(Results<T> response) {
|
||||
return response != null && response.code == SUCCESS_CODE;
|
||||
}
|
||||
|
||||
|
||||
public void setErrorCodeEnum(int code, String msg) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public static <T> Results.ResultsBuilder<T> builder() {
|
||||
return new Results.ResultsBuilder();
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return this.msg;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return this.data;
|
||||
}
|
||||
|
||||
public String getRid() {
|
||||
return rid;
|
||||
}
|
||||
|
||||
public void setRid(String rid) {
|
||||
this.rid = rid;
|
||||
}
|
||||
|
||||
public void setCode(final int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public void setMsg(final String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public void setData(final T data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
protected boolean canEqual(final Object other) {
|
||||
return other instanceof Results;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Results(code=" + this.getCode() + ", msg=" + this.getMsg() + ", data=" + this.getData() + ")";
|
||||
}
|
||||
|
||||
public static class ResultsBuilder<T> {
|
||||
private int code;
|
||||
private String msg;
|
||||
private T data;
|
||||
|
||||
ResultsBuilder() {
|
||||
}
|
||||
|
||||
public Results.ResultsBuilder<T> code(final int code) {
|
||||
this.code = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Results.ResultsBuilder<T> msg(final String msg) {
|
||||
this.msg = msg;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Results.ResultsBuilder<T> data(final T data) {
|
||||
this.data = data;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Results<T> build() {
|
||||
return new Results(this.code, this.msg, this.data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Results.ResultsBuilder(code=" + this.code + ", msg=" + this.msg + ", data=" + this.data + ")";
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,25 @@
|
||||
package top.baogutang.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:00
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum TokenCodeEnum {
|
||||
/**
|
||||
* 未获取到token
|
||||
*/
|
||||
AUTH_TOKEN_EMPTY(-200, "未获取到token"),
|
||||
AUTH_FAILED(-200, "无权限"),
|
||||
AUTH_TIME_OUT(-200, "token已过期"),
|
||||
AUTH_TOKEN_ILLEGAL(-200, "Token不合法");
|
||||
|
||||
public int code;
|
||||
|
||||
public String message;
|
||||
}
|
||||
@ -0,0 +1,39 @@
|
||||
package top.baogutang.common.exceptions;
|
||||
|
||||
import top.baogutang.common.constants.ErrorCodeEnum;
|
||||
import top.baogutang.common.domain.Results;
|
||||
|
||||
/**
|
||||
* @description: 业务异常
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 11:48
|
||||
*/
|
||||
public class BusinessException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = -8485514816508612287L;
|
||||
|
||||
private int code = Results.FAIL_CODE;
|
||||
|
||||
public BusinessException(int code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
|
||||
public BusinessException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public BusinessException(ErrorCodeEnum errorCodeEnum) {
|
||||
super(errorCodeEnum.getMsg());
|
||||
this.code = errorCodeEnum.getCode();
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,75 @@
|
||||
package top.baogutang.common.exceptions;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.catalina.connector.ClientAbortException;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.validation.ObjectError;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import top.baogutang.common.domain.Results;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @description: 全局异常处理
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:23
|
||||
*/
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
|
||||
public GlobalExceptionHandler() {
|
||||
//
|
||||
}
|
||||
|
||||
@ExceptionHandler({Throwable.class})
|
||||
public Results<Object> handleException(Throwable e) {
|
||||
log.error("请求发生错误,错误信息:{}", e.getMessage(), e);
|
||||
return Results.failed("出错啦,请稍后再试哟~");
|
||||
}
|
||||
|
||||
|
||||
@ExceptionHandler({Exception.class})
|
||||
public Results<Object> handleException(Exception e) {
|
||||
log.error("请求发生错误,错误信息:", e);
|
||||
return Results.failed("服务器出错啦,请稍后再试哟~");
|
||||
}
|
||||
|
||||
@ExceptionHandler({ClientAbortException.class})
|
||||
public Results<Object> handleClientAbortException() {
|
||||
log.error("ClientAbortException: java.io.IOException: Broken pipe: {}", "客户端链接断开");
|
||||
return Results.failed(300, "服务器出错啦,请稍后再试哟~");
|
||||
}
|
||||
|
||||
@ExceptionHandler({IllegalArgumentException.class, MissingServletRequestParameterException.class, HttpMediaTypeNotSupportedException.class, HttpRequestMethodNotSupportedException.class})
|
||||
public Results<Object> handleMultiException(Exception e) {
|
||||
log.error("请求发生错误,错误信息:{}", e.getMessage(), e);
|
||||
return Results.failed(300, e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler({BusinessException.class})
|
||||
public Results<Object> businessException(BusinessException e) {
|
||||
log.error("请求发生错误,code:{},message:{}", e.getCode(), e.getMessage());
|
||||
return Results.failed(e.getCode(), e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler({MethodArgumentNotValidException.class})
|
||||
public Results<Object> parameterExceptionHandler(MethodArgumentNotValidException e) {
|
||||
BindingResult exceptions = e.getBindingResult();
|
||||
if (exceptions.hasErrors()) {
|
||||
List<ObjectError> errors = exceptions.getAllErrors();
|
||||
if (!errors.isEmpty()) {
|
||||
FieldError fieldError = (FieldError) errors.get(0);
|
||||
return Results.failed(301, fieldError.getDefaultMessage());
|
||||
}
|
||||
}
|
||||
return Results.failed(301, e.getMessage());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,24 @@
|
||||
package top.baogutang.common.properties;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/16 : 12:50
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@RefreshScope
|
||||
@ConfigurationProperties(prefix = "wx.msg-push")
|
||||
public class WxMsgPushProperties {
|
||||
|
||||
private String appToken;
|
||||
|
||||
private Set<Long> topicIds;
|
||||
}
|
||||
@ -0,0 +1,161 @@
|
||||
package top.baogutang.common.utils;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.TypeReference;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import top.baogutang.common.constants.ErrorCodeEnum;
|
||||
import top.baogutang.common.exceptions.BusinessException;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 说明:网络请求工具
|
||||
*
|
||||
* @author nikooh
|
||||
*/
|
||||
@Slf4j
|
||||
public final class HttpUtils {
|
||||
private static final String CHARSET_NAME = "UTF-8";
|
||||
|
||||
private HttpUtils() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送post请求
|
||||
*
|
||||
* @param data 发送的数据
|
||||
* @param url 请求后台的url
|
||||
* @return 发送的result结果
|
||||
*/
|
||||
public static <T> T post(Object data, String url, TypeReference<T> type) {
|
||||
try {
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
String dataStr = JSON.toJSONString(data);
|
||||
|
||||
URL cUrl = new URL(url);
|
||||
HttpURLConnection urlConnection = (HttpURLConnection) cUrl.openConnection();
|
||||
urlConnection.setConnectTimeout(60000);
|
||||
urlConnection.setReadTimeout(60000);
|
||||
urlConnection.setUseCaches(false);
|
||||
urlConnection.setRequestMethod("POST");
|
||||
//设置请求属性
|
||||
urlConnection.setRequestProperty("Content-Type", "application/json");
|
||||
urlConnection.setRequestProperty("Charset", CHARSET_NAME);
|
||||
urlConnection.setDoOutput(true);
|
||||
urlConnection.connect();
|
||||
OutputStream outputStream = urlConnection.getOutputStream();
|
||||
outputStream.write(dataStr.getBytes(StandardCharsets.UTF_8));
|
||||
outputStream.flush();
|
||||
return dealConnect(urlConnection, type);
|
||||
} catch (Exception e) {
|
||||
log.error(">>>>>>>>>>请求异常:{}<<<<<<<<<<", e.getMessage(), e);
|
||||
throw new BusinessException(ErrorCodeEnum.E_BIZ_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T get(String path, TypeReference<T> type) {
|
||||
return get(null, path, type);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送get请求
|
||||
*/
|
||||
public static <T> T get(Map<String, Object> data, String url, TypeReference<T> type) {
|
||||
try {
|
||||
String query = parseMap2Query(data);
|
||||
if (!query.isEmpty()) {
|
||||
url = url + "?" + query;
|
||||
}
|
||||
URL cUrl = new URL(url);
|
||||
HttpURLConnection urlConnection = (HttpURLConnection) cUrl.openConnection();
|
||||
urlConnection.setConnectTimeout(60000);
|
||||
urlConnection.setReadTimeout(60000);
|
||||
urlConnection.setUseCaches(false);
|
||||
urlConnection.setRequestMethod("GET");
|
||||
//设置请求属性
|
||||
urlConnection.setRequestProperty("Charset", CHARSET_NAME);
|
||||
urlConnection.setDoOutput(true);
|
||||
urlConnection.connect();
|
||||
return dealConnect(urlConnection, type);
|
||||
} catch (Exception e) {
|
||||
log.error(">>>>>>>>>>请求异常:{}<<<<<<<<<<", e.getMessage(), e);
|
||||
throw new BusinessException(ErrorCodeEnum.E_BIZ_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把map转成query查询字符串
|
||||
*/
|
||||
private static String parseMap2Query(Map<String, Object> data) {
|
||||
if (data == null || data.size() <= 0) {
|
||||
return "";
|
||||
}
|
||||
Set<Map.Entry<String, Object>> entries = data.entrySet();
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
for (Map.Entry<String, Object> entry : entries) {
|
||||
if (stringBuilder.length() > 0) {
|
||||
stringBuilder.append("&");
|
||||
}
|
||||
stringBuilder.append(entry.getKey()).append("=").append(entry.getValue());
|
||||
}
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 处理连接以后的状态信息
|
||||
*
|
||||
* @param urlConnection 打开的连接
|
||||
* @return 返回发送结果
|
||||
*/
|
||||
private static <T> T dealConnect(HttpURLConnection urlConnection, TypeReference<T> type) {
|
||||
try {
|
||||
int responseCode = urlConnection.getResponseCode();
|
||||
if (responseCode != 200) {
|
||||
throw new BusinessException(ErrorCodeEnum.E_BIZ_ERROR);
|
||||
}
|
||||
InputStream inputStream = urlConnection.getInputStream();
|
||||
String res = inputStream2String(inputStream);
|
||||
if (res == null || res.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return JSON.parseObject(res, type);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error(">>>>>>>>>>请求异常:{}<<<<<<<<<<", e.getMessage(), e);
|
||||
throw new BusinessException(ErrorCodeEnum.E_BIZ_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从输入流中读取内容到字符串
|
||||
*
|
||||
* @param inputStream 输入路
|
||||
* @return 返回字符串
|
||||
*/
|
||||
private static String inputStream2String(InputStream inputStream) {
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
int len = 0;
|
||||
byte[] bytes = new byte[4096];
|
||||
try {
|
||||
while ((len = inputStream.read(bytes)) != -1) {
|
||||
outputStream.write(bytes, 0, len);
|
||||
}
|
||||
return new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
log.error(">>>>>>>>>>请求异常:{}<<<<<<<<<<", e.getMessage(), e);
|
||||
throw new BusinessException(ErrorCodeEnum.E_BIZ_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,22 @@
|
||||
package top.baogutang.common.utils;
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @author: nikooh
|
||||
* @date: 2023/06/15 : 12:03
|
||||
*/
|
||||
public class UserThreadLocal {
|
||||
private static final ThreadLocal<Long> userThread = new ThreadLocal<>();
|
||||
|
||||
public static void set(Long userId) {
|
||||
userThread.set(userId);
|
||||
}
|
||||
|
||||
public static Long get() {
|
||||
return userThread.get();
|
||||
}
|
||||
|
||||
public static void remove() {
|
||||
userThread.remove();
|
||||
}
|
||||
}
|
||||
10
baogutang-common/src/main/resources/script/accquire.lua
Normal file
10
baogutang-common/src/main/resources/script/accquire.lua
Normal file
@ -0,0 +1,10 @@
|
||||
local limit = tonumber(ARGV[1])
|
||||
local current = tonumber(redis.call('get', KEYS[1]) or '0')
|
||||
if current + 1 > limit
|
||||
then
|
||||
return false
|
||||
else
|
||||
redis.call('INCRBY', KEYS[1], '1')
|
||||
redis.call('expire', KEYS[1], '2')
|
||||
end
|
||||
return true
|
||||
25
baogutang-common/src/main/resources/script/ipLimit.lua
Normal file
25
baogutang-common/src/main/resources/script/ipLimit.lua
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
--- Generated by EmmyLua(https://github.com/EmmyLua)
|
||||
--- Created by developer.
|
||||
--- DateTime: 2022/6/21 14:26
|
||||
---
|
||||
|
||||
local val = redis.call('incr', KEYS[1])
|
||||
local ttl = redis.call('ttl', KEYS[1])
|
||||
|
||||
--获取ARGV内的参数并打印
|
||||
local expire = ARGV[1]
|
||||
local times = ARGV[2]
|
||||
|
||||
if val == 1 then
|
||||
redis.call('expire', KEYS[1], tonumber(expire))
|
||||
else
|
||||
if ttl == -1 then
|
||||
redis.call('expire', KEYS[1], tonumber(expire))
|
||||
end
|
||||
end
|
||||
|
||||
if val > tonumber(times) then
|
||||
return false
|
||||
end
|
||||
return true
|
||||
155
pom.xml
Normal file
155
pom.xml
Normal file
@ -0,0 +1,155 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.3.2.RELEASE</version>
|
||||
</parent>
|
||||
<groupId>top.baogutang</groupId>
|
||||
<artifactId>baogutang-parent</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
||||
<modules>
|
||||
<module>baogutang-admin</module>
|
||||
<module>baogutang-business</module>
|
||||
<module>baogutang-common</module>
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<spring.boot.version>2.3.2.RELEASE</spring.boot.version>
|
||||
<spring-cloud.version>Hoxton.SR9</spring-cloud.version>
|
||||
<spring.cloud.alibaba.version>2.2.6.RELEASE</spring.cloud.alibaba.version>
|
||||
<aliyun.log.version>0.1.13</aliyun.log.version>
|
||||
<protobuf.java.version>2.5.0</protobuf.java.version>
|
||||
<fastjson.version>1.2.83</fastjson.version>
|
||||
<jwt.token.version>0.9.0</jwt.token.version>
|
||||
<lombok.version>1.18.12</lombok.version>
|
||||
<guava.vsersion>29.0-jre</guava.vsersion>
|
||||
<commons.pool2.version>2.10.0</commons.pool2.version>
|
||||
<httpClient.version>4.5.3</httpClient.version>
|
||||
<springfox-boot.version>3.0.0</springfox-boot.version>
|
||||
<mybatis.plus.boot.version>3.4.2</mybatis.plus.boot.version>
|
||||
<commons.lang.version>2.6</commons.lang.version>
|
||||
<ons.version>1.8.8.1.Final</ons.version>
|
||||
<okhttp3.version>4.9.3</okhttp3.version>
|
||||
<aliyun.oss.verson>3.8.1</aliyun.oss.verson>
|
||||
<aliyun.sdk.core.verson>4.1.1</aliyun.sdk.core.verson>
|
||||
<aliyun.sdk.green.verson>3.6.5</aliyun.sdk.green.verson>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>${spring-cloud.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>${spring.cloud.alibaba.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun.openservices</groupId>
|
||||
<artifactId>aliyun-log-logback-appender</artifactId>
|
||||
<version>${aliyun.log.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.protobuf</groupId>
|
||||
<artifactId>protobuf-java</artifactId>
|
||||
<version>${protobuf.java.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>${fastjson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt</artifactId>
|
||||
<version>${jwt.token.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.vsersion}</version>
|
||||
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-pool2</artifactId>
|
||||
<version>${commons.pool2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-lang</groupId>
|
||||
<artifactId>commons-lang</artifactId>
|
||||
<version>${commons.lang.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpClient.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
<version>${mybatis.plus.boot.version}</version>
|
||||
</dependency>
|
||||
<!-- swagger -->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-boot-starter</artifactId>
|
||||
<version>${springfox-boot.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.aliyun.openservices</groupId>
|
||||
<artifactId>ons-client</artifactId>
|
||||
<!--以下版本号请替换为Java SDK的最新版本号-->
|
||||
<version>${ons.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>${okhttp3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.aliyun.oss</groupId>
|
||||
<artifactId>aliyun-sdk-oss</artifactId>
|
||||
<version>${aliyun.oss.verson}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||
<version>${aliyun.sdk.core.verson}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-green</artifactId>
|
||||
<version>${aliyun.sdk.green.verson}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
</project>
|
||||
Loading…
Reference in New Issue
Block a user