spring boot 3.06

This commit is contained in:
Jesse-Ma
2023-05-25 09:35:17 +08:00
parent c7d135cc15
commit 668a022a07
16 changed files with 232 additions and 222 deletions

17
pom.xml
View File

@@ -6,7 +6,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
<version>3.0.6</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.flagnote</groupId>
@@ -20,7 +20,8 @@
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.compilerVersion>17</maven.compiler.compilerVersion>
<spring-cloud.version>2022.0.2</spring-cloud.version>
<docker.image.prefix>flagnote</docker.image.prefix>
<docker.repostory>registry.openif.com:5000</docker.repostory>
<docker.registry.name>flagnote</docker.registry.name>
</properties>
<dependencies>
<dependency>
@@ -56,7 +57,7 @@
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.22</version>
<version>5.8.18</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -117,11 +118,15 @@
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>1.2.2</version>
<configuration>
<googleContainerRegistryEnabled>false</googleContainerRegistryEnabled>
<dockerHost>http://rancher:42375</dockerHost>
<serverId>docker-openif</serverId>
<registryUrl>http://${docker.repository}</registryUrl>
<pushImage>true</pushImage>
<dockerHost>http://144.34.221.20:42375</dockerHost>
<imageName>
${docker.image.prefix}/${project.artifactId}:${project.version}</imageName>
${docker.repostory}/${docker.registry.name}/${project.artifactId}:${project.version}
</imageName>
<dockerDirectory>src/main/docker</dockerDirectory>
<resources>
<resource>

View File

@@ -10,18 +10,18 @@ import reactor.core.publisher.Mono;
@Configuration
public class ApiLimiterConfiguration {
@Bean(name="remoteSessionKeyResolver")
@Bean(name = "remoteSessionKeyResolver")
public KeyResolver remoteSessionKeyResolver() {
return exchange -> Mono.just(exchange.getSession().block().getId());
}
@Bean(name="noteKeyResolver")
@Bean(name = "noteKeyResolver")
public KeyResolver noteKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getPath().toString());
}
@Primary
@Bean(name="remoteAddrKeyResolver")
@Bean(name = "remoteAddrKeyResolver")
public KeyResolver remoteAddrKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
}

View File

@@ -5,8 +5,6 @@ import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
@@ -16,7 +14,6 @@ import org.springframework.cloud.client.loadbalancer.RequestData;
import org.springframework.cloud.client.loadbalancer.RequestDataContext;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.NoopServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.SelectedInstanceCallback;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
@@ -28,17 +25,17 @@ import reactor.core.publisher.Mono;
@Slf4j
public class BizKeyLoadBalancerClient implements ReactorServiceInstanceLoadBalancer {
private final String serviceId;
private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;
private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;
public BizKeyLoadBalancerClient(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider,
String serviceId) {
this.serviceId = serviceId;
this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
}
@SuppressWarnings("rawtypes")
@Override
public Mono<Response<ServiceInstance>> choose(Request request) {
@@ -47,7 +44,7 @@ public class BizKeyLoadBalancerClient implements ReactorServiceInstanceLoadBalan
return supplier.get(request).next()
.map(serviceInstances -> processInstanceResponse(request, supplier, serviceInstances));
}
@SuppressWarnings("rawtypes")
private Response<ServiceInstance> processInstanceResponse(Request request, ServiceInstanceListSupplier supplier,
List<ServiceInstance> serviceInstances) {
@@ -57,7 +54,7 @@ public class BizKeyLoadBalancerClient implements ReactorServiceInstanceLoadBalan
}
return serviceInstanceResponse;
}
@SuppressWarnings("rawtypes")
private Response<ServiceInstance> getInstanceResponse(Request request, List<ServiceInstance> instances) {
if (instances.isEmpty()) {
@@ -66,25 +63,25 @@ public class BizKeyLoadBalancerClient implements ReactorServiceInstanceLoadBalan
}
return new EmptyResponse();
}
RequestDataContext rdContext = (RequestDataContext)request.getContext();
RequestDataContext rdContext = (RequestDataContext) request.getContext();
RequestData rdata = rdContext.getClientRequest();
String path = rdata.getUrl().getPath();
String pattern = "^/note/([abcdefhikmnopqstuvwxyz23456789]{16})(\\.txt|/noteMeta|/delete)?$";
Pattern pt = Pattern.compile(pattern);
Matcher m = pt.matcher(path);
//默认随机
int index = ThreadLocalRandom.current().nextInt(instances.size());
//如果有key则为key分配指定服务。
if(m.find()) {
String mixKey = BizKeyUtils.mixKey(m.group(1));
index = Math.abs(mixKey.hashCode())%instances.size();
}
Pattern pt = Pattern.compile(pattern);
Matcher m = pt.matcher(path);
// 默认随机
int index = ThreadLocalRandom.current().nextInt(instances.size());
// 如果有key则为key分配指定服务。
if (m.find()) {
String mixKey = BizKeyUtils.mixKey(m.group(1));
index = Math.abs(mixKey.hashCode()) % instances.size();
}
ServiceInstance instance = instances.get(index);
log.info("path:{},service:{}",path,instance.getUri().toString());
log.info("path:{},service:{}", path, instance.getUri().toString());
return new DefaultResponse(instance);
}

View File

@@ -9,9 +9,11 @@ import org.springframework.core.env.Environment;
//@Configuration 必须注释掉
public class BkrLoadBalancerConfiguration {
@Bean
public ReactorLoadBalancer<ServiceInstance> reactorServiceInstanceLoadBalancer(Environment environment, LoadBalancerClientFactory loadBalancerClientFactory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new BizKeyLoadBalancerClient(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
}
@Bean
public ReactorLoadBalancer<ServiceInstance> reactorServiceInstanceLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new BizKeyLoadBalancerClient(
loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
}
}

View File

@@ -1,7 +1,5 @@
package com.flagnote.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
@@ -11,28 +9,27 @@ import org.springframework.web.util.pattern.PathPatternParser;
public class GwCorsFilter {
// @Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.setAllowCredentials(true); // 允许cookies跨域
config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI*表示全部允许在SpringMVC中如果设成*会自动转成当前请求头中的Origin
config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
config.addAllowedMethod("OPTIONS");// 允许提交请求的方法类型,*表示全部允许
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
config.setAllowCredentials(true); // 允许cookies跨域
config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI*表示全部允许在SpringMVC中如果设成*会自动转成当前请求头中的Origin
config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
config.addAllowedMethod("OPTIONS");// 允许提交请求的方法类型,*表示全部允许
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
UrlBasedCorsConfigurationSource source =
new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
return new CorsWebFilter(source);
}
}

View File

@@ -8,8 +8,8 @@ import org.springframework.web.reactive.config.WebFluxConfigurer;
@Configuration
@EnableWebFlux
public class WebFluxWebConfig implements WebFluxConfigurer {
@Override
public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
configurer.defaultCodecs().maxInMemorySize(10 * 1024 * 1024);
}
@Override
public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
configurer.defaultCodecs().maxInMemorySize(10 * 1024 * 1024);
}
}

View File

@@ -12,7 +12,6 @@ import org.springframework.web.server.ServerWebExchange;
import com.flagnote.gateway.utils.BizKeyUtils;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import reactor.core.publisher.Mono;
@@ -30,18 +29,17 @@ public class ValidateNoteCipherFilter implements GatewayFilter, Ordered {
String cipher = body.getStr("cipher");
String initTime = body.getStr("initTime");
String key = body.getStr("key");
if (!noteKey.equals(key)) {
exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
return exchange.getResponse().setComplete();
}
if (!BizKeyUtils.validateCipher(noteKey,initTime, cipher)) {
if (!BizKeyUtils.validateCipher(noteKey, initTime, cipher)) {
exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}

View File

@@ -8,7 +8,6 @@ import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
@@ -33,7 +32,8 @@ public class ValidateNoteKeyFilter implements GatewayFilter, Ordered {
if (!BizKeyUtils.validateKey(noteKey)) {
NoteMeta meta = new NoteMeta();
DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(JsonUtils.toJson(meta).getBytes(StandardCharsets.UTF_8));
DataBuffer dataBuffer = exchange.getResponse().bufferFactory()
.wrap(JsonUtils.toJson(meta).getBytes(StandardCharsets.UTF_8));
return exchange.getResponse().writeWith(Flux.just(dataBuffer));
}

View File

@@ -1,22 +1,13 @@
package com.flagnote.gateway.filter.factory;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory.NameConfig;
import org.springframework.cloud.gateway.support.GatewayToStringStyler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import com.flagnote.gateway.filter.ValidateNoteCipherFilter;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
@Slf4j
@Component
@@ -25,15 +16,14 @@ public class ValidateNoteCipherGatewayFilterFactory
@Autowired
private ValidateNoteCipherFilter validateNoteCipherFilter;
public ValidateNoteCipherGatewayFilterFactory() {
super(NameConfig.class);
}
@Override
public GatewayFilter apply(NameConfig config) {
return validateNoteCipherFilter;
}
}

View File

@@ -1,22 +1,13 @@
package com.flagnote.gateway.filter.factory;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory.NameConfig;
import org.springframework.cloud.gateway.support.GatewayToStringStyler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import com.flagnote.gateway.filter.ValidateNoteKeyFilter;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
@Slf4j
@Component
@@ -25,8 +16,7 @@ public class ValidateNoteKeyGatewayFilterFactory
@Autowired
private ValidateNoteKeyFilter validateNoteKeyFilter;
public ValidateNoteKeyGatewayFilterFactory() {
super(NameConfig.class);
}
@@ -35,12 +25,12 @@ public class ValidateNoteKeyGatewayFilterFactory
// public List<String> shortcutFieldOrder() {
// return Arrays.asList("name");
// }
@Override
public GatewayFilter apply(NameConfig config) {
return validateNoteKeyFilter;
// return new GatewayFilter() {
// @Override
// public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

View File

@@ -84,14 +84,13 @@ public class BizKeyUtils {
return Integer.parseInt(String.valueOf(new Date().getTime()).substring(0, 4));
}
public static String getCipher(String key,String initTime) {
return md5(key +"#"+ MIX_STRING + "#" + initTime);
public static String getCipher(String key, String initTime) {
return md5(key + "#" + MIX_STRING + "#" + initTime);
}
public static Boolean validateCipher(String key,String initTime,String cipher) {
return md5(key +"#"+ MIX_STRING + "#" + initTime).equals(cipher);
public static Boolean validateCipher(String key, String initTime, String cipher) {
return md5(key + "#" + MIX_STRING + "#" + initTime).equals(cipher);
}
public static String getSecretKey(String key, String password) {
return md5(key + md5(MIX_STRING + password));

View File

@@ -14,99 +14,96 @@ import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class JsonUtils {
private static ObjectMapper om = new ObjectMapper();
static {
// 对象的所有字段全部列入还是其他的选项可以忽略null等
om.setSerializationInclusion(Include.ALWAYS);
// 设置Date类型的序列化及反序列化格式
om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 忽略空Bean转json的错误
om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// 忽略未知属性防止json字符串中存在java对象中不存在对应属性的情况出现错误
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 注册一个时间序列化及反序列化的处理模块用于解决jdk8中localDateTime等的序列化问题
om.registerModule(new JavaTimeModule());
}
/**
* 对象 => json字符串
*
* @param obj 源对象
*/
public static <T> String toJson(T obj) {
String json = null;
if (obj != null) {
try {
json = om.writeValueAsString(obj);
} catch (JsonProcessingException e) {
log.warn(e.getMessage(), e);
throw new IllegalArgumentException(e.getMessage());
}
}
return json;
}
/**
* json字符串 => 对象
*
* @param json 源json串
* @param clazz 对象类
* @param <T> 泛型
*/
public static <T> T parse(String json, Class<T> clazz) {
return parse(json, clazz, null);
}
/**
* json字符串 => 对象
*
* @param json 源json串
* @param type 对象类型
* @param <T> 泛型
*/
public static <T> T parse(String json, TypeReference<T> type) {
return parse(json, null, type);
}
/**
* json => 对象处理方法
* <br>
* 参数clazz和type必须一个为null另一个不为null
* <br>
* 此方法不对外暴露访问权限为private
*
* @param json 源json串
* @param clazz 对象类
* @param type 对象类型
* @param <T> 泛型
*/
private static <T> T parse(String json, Class<T> clazz, TypeReference<T> type) {
T obj = null;
if (StringUtils.hasLength(json)) {
try {
if (clazz != null) {
obj = om.readValue(json, clazz);
} else {
obj = om.readValue(json, type);
}
} catch (IOException e) {
log.warn(e.getMessage(), e);
throw new IllegalArgumentException(e.getMessage());
}
}
return obj;
}
private static ObjectMapper om = new ObjectMapper();
static {
// 对象的所有字段全部列入还是其他的选项可以忽略null等
om.setSerializationInclusion(Include.ALWAYS);
// 设置Date类型的序列化及反序列化格式
om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 忽略空Bean转json的错误
om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// 忽略未知属性防止json字符串中存在java对象中不存在对应属性的情况出现错误
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 注册一个时间序列化及反序列化的处理模块用于解决jdk8中localDateTime等的序列化问题
om.registerModule(new JavaTimeModule());
}
/**
* 对象 => json字符串
*
* @param obj 源对象
*/
public static <T> String toJson(T obj) {
String json = null;
if (obj != null) {
try {
json = om.writeValueAsString(obj);
} catch (JsonProcessingException e) {
log.warn(e.getMessage(), e);
throw new IllegalArgumentException(e.getMessage());
}
}
return json;
}
/**
* json字符串 => 对象
*
* @param json 源json串
* @param clazz 对象类
* @param <T> 泛型
*/
public static <T> T parse(String json, Class<T> clazz) {
return parse(json, clazz, null);
}
/**
* json字符串 => 对象
*
* @param json 源json串
* @param type 对象类型
* @param <T> 泛型
*/
public static <T> T parse(String json, TypeReference<T> type) {
return parse(json, null, type);
}
/**
* json => 对象处理方法 <br>
* 参数clazz和type必须一个为null另一个不为null <br>
* 此方法不对外暴露访问权限为private
*
* @param json 源json串
* @param clazz 对象类
* @param type 对象类型
* @param <T> 泛型
*/
private static <T> T parse(String json, Class<T> clazz, TypeReference<T> type) {
T obj = null;
if (StringUtils.hasLength(json)) {
try {
if (clazz != null) {
obj = om.readValue(json, clazz);
} else {
obj = om.readValue(json, type);
}
} catch (IOException e) {
log.warn(e.getMessage(), e);
throw new IllegalArgumentException(e.getMessage());
}
}
return obj;
}
}

View File

@@ -5,25 +5,26 @@ import java.io.Serializable;
import lombok.Data;
@Data
public class NoteMeta implements Serializable {/**
*
*/
public class NoteMeta implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8234044213813670440L;
/**
*
*/
/**
*
*/
private String key;
private Integer state;
private String cipher;
private Integer lock;
private String md5;
private Long serverTime;
private Long ttl;

View File

@@ -6,15 +6,15 @@ import java.security.SecureRandom;
public class RandomUtils {
public static SecureRandom sr = null;
static {
try {
sr = SecureRandom.getInstanceStrong();
} catch (NoSuchAlgorithmException e) {
sr = new SecureRandom();
}
try {
sr = SecureRandom.getInstanceStrong();
} catch (NoSuchAlgorithmException e) {
sr = new SecureRandom();
}
}
public static Integer nextInt(Integer num) {
return sr.nextInt(num);
}

View File

@@ -5,7 +5,6 @@ spring:
config:
name: flagnote-gateway
profile: prd
uri: http://flagnote-config-01:8080/flagnote-config,http://flagnote-config-02:8080/flagnote-config
uri: http://flagnote-config-01:8080/flagnote-config
config:
import: optional:configserver:http://flagnote-config-01:8080/,optional:configserver:http://flagnote-config-02:8080/
import: optional:configserver:http://flagnote-config-01:8080/

View File

@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<springProperty scope="context" name="logPath" source="logback.logPath"/>
<property name="pattern" value="[%date{yyyy-MM-dd HH:mm:ss.SSS}] %X{logthreadId} %-5level %logger{80} %method %line - %msg%n"/>
<property name="charsetEncoding" value="UTF-8"/>
<property name="LOG_HOME" value="${logPath}"/>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${pattern}</pattern>
<charset>${charsetEncoding}</charset>
</encoder>
</appender>
<appender name="infoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<append>true</append>
<encoder>
<pattern>${pattern}</pattern>
<charset>${charsetEncoding}</charset>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>
${LOG_HOME}${file.separator}%d{yyMMdd}_info_%i.log
</fileNamePattern>
<maxHistory>30</maxHistory>
<maxFileSize>20MB</maxFileSize>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
</appender>
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="infoLog"/>
</root>
</configuration>