init commit

This commit is contained in:
ycl
2026-05-18 14:16:17 +08:00
commit 3bad77d34b
46 changed files with 1799 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
> 本模块存放公共组件
``` \-- *.utils(工具类; package)
\-- *.enums(公共枚举; package)
\-- *.constants(公共常量; package)
```

17
template/common/pom.xml Normal file
View File

@@ -0,0 +1,17 @@
<?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>{{ .groupId }}</groupId>
<artifactId>{{ .artifactId }}</artifactId>
<version>${revision}</version>
</parent>
<groupId>{{ .groupId }}</groupId>
<artifactId>{{ .artifactId }}-common</artifactId>
<dependencies>
</dependencies>
</project>

View File

@@ -0,0 +1,2 @@
> 本模块存放公共常量
``` \-- *Constant.java

View File

@@ -0,0 +1,2 @@
> 本模块存放公共枚举
``` \-- *Enum.java

View File

@@ -0,0 +1,25 @@
package {{ .package }}.common.mybatisplus;
import com.baomidou.mybatisplus.extension.ddl.IDdl;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.function.Consumer;
import javax.sql.DataSource;
@Component
public class EmptyDdl implements IDdl {
public void execute() {
// 空实现
}
@Override
public void runScript(Consumer<DataSource> consumer) {}
@Override
public List<String> getSqlFiles() {
return null;
}
}

View File

@@ -0,0 +1,60 @@
package {{ .package }}.common.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
@Configuration
@EnableConfigurationProperties({RedisPoolProperties.class})
@ConditionalOnProperty(name = "redis-config.pool.hostAndPort")
public class RedisPoolConfig {
@Autowired
private RedisPoolProperties redisPoolProperties;
@Value("${redis-config.pool.password:}")
private String password;
private JedisPoolConfig initPoolConfig() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(redisPoolProperties.getMaxTotal());
poolConfig.setMaxIdle(redisPoolProperties.getMaxIdle());
poolConfig.setMinIdle(redisPoolProperties.getMinIdle());
poolConfig.setNumTestsPerEvictionRun(redisPoolProperties.getNumTestsPerEvictionRun());
poolConfig.setTestOnBorrow(redisPoolProperties.isTestOnBorrow());
poolConfig.setTestOnReturn(redisPoolProperties.isTestOnReturn());
poolConfig.setTestWhileIdle(redisPoolProperties.isTestWhileIdle());
poolConfig.setBlockWhenExhausted(redisPoolProperties.isBlockWhenExhausted());
poolConfig.setJmxEnabled(redisPoolProperties.isJmxEnabled());
poolConfig.setLifo(redisPoolProperties.isLifo());
poolConfig.setNumTestsPerEvictionRun(redisPoolProperties.getNumTestsPerEvictionRun());
poolConfig.setTestOnBorrow(false);
return poolConfig;
}
/**
* create jedis poll
*
*/
@Bean
public JedisPool getRedisPool() {
String host = StrUtil.subBefore(redisPoolProperties.getHostAndPort(), ":", false);
int port = Integer.parseInt(StrUtil.subAfter(redisPoolProperties.getHostAndPort(), ":", false));
if(StrUtil.isNotEmpty(this.password)) {
return new JedisPool(initPoolConfig(),host,port ,1000, password);
}else{
return new JedisPool(initPoolConfig(),host,port);
}
}
}

View File

@@ -0,0 +1,145 @@
package {{ .package }}.common.redis;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@ConfigurationProperties(prefix = "redis-config.pool")
public class RedisPoolProperties {
private String hostAndPort;
private int maxTotal;
private int maxIdle;
private int minIdle;
private Long maxWaitMillis;
private Long timeBetweenEvictionRunsMillis;
private Long minEvictableIdleTimeMillis;
private Long softMinEvictableIdleTimeMillis;
private boolean testOnBorrow;
private boolean testOnReturn;
private boolean testWhileIdle;
private boolean blockWhenExhausted;
private boolean jmxEnabled;
private boolean lifo;
private int numTestsPerEvictionRun;
public String getHostAndPort() {
return hostAndPort;
}
public void setHostAndPort(String hostAndPort) {
this.hostAndPort = hostAndPort;
}
public int getMaxTotal() {
return maxTotal;
}
public void setMaxTotal(int maxTotal) {
this.maxTotal = maxTotal;
}
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public Long getMaxWaitMillis() {
return maxWaitMillis;
}
public void setMaxWaitMillis(Long maxWaitMillis) {
this.maxWaitMillis = maxWaitMillis;
}
public Long getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(Long timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public Long getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(Long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public Long getSoftMinEvictableIdleTimeMillis() {
return softMinEvictableIdleTimeMillis;
}
public void setSoftMinEvictableIdleTimeMillis(Long softMinEvictableIdleTimeMillis) {
this.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public boolean isBlockWhenExhausted() {
return blockWhenExhausted;
}
public void setBlockWhenExhausted(boolean blockWhenExhausted) {
this.blockWhenExhausted = blockWhenExhausted;
}
public boolean isJmxEnabled() {
return jmxEnabled;
}
public void setJmxEnabled(boolean jmxEnabled) {
this.jmxEnabled = jmxEnabled;
}
public boolean isLifo() {
return lifo;
}
public void setLifo(boolean lifo) {
this.lifo = lifo;
}
public int getNumTestsPerEvictionRun() {
return numTestsPerEvictionRun;
}
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
this.numTestsPerEvictionRun = numTestsPerEvictionRun;
}
}

View File

@@ -0,0 +1,48 @@
package {{ .package }}.common.response;
import java.text.*;
import java.util.Calendar;
import java.util.Date;
public class MyDateFormat extends DateFormat {
private static final long serialVersionUID = -4580955831439573829L;
private static final String customDateFormat = "yyyy-MM-dd HH:mm:ss";
private DateFormat dateFormat;
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public MyDateFormat(DateFormat dateFormat) {
this.calendar = Calendar.getInstance();
this.dateFormat = dateFormat;
}
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
return this.dateFormat.format(date, toAppendTo, fieldPosition);
}
public Date parse(String source, ParsePosition pos) {
Date date = null;
if (source.length() == "yyyy-MM-dd HH:mm:ss".length()) {
date = this.simpleDateFormat.parse(source, pos);
} else {
date = this.dateFormat.parse(source, pos);
}
return date;
}
public Date parse(String source) throws ParseException {
Date date = null;
if (source.length() == "yyyy-MM-dd HH:mm:ss".length()) {
date = this.simpleDateFormat.parse(source);
} else {
date = this.dateFormat.parse(source);
}
return date;
}
public Object clone() {
Object format = this.dateFormat.clone();
return new MyDateFormat((DateFormat)format);
}
}

View File

@@ -0,0 +1,118 @@
package {{ .package }}.common.response;
import com.vs.common.util.rpc.pub.FailData;
import com.vs.ox.common.exception.ErrorCode;
import com.vs.ox.common.exception.IgnoredException;
import com.vs.ox.common.utils.ObjectMapperFactory;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Path;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Slf4j
public class ResponseJsonExceptionResolver extends AbstractHandlerExceptionResolver
implements InitializingBean {
private HttpMessageConverter messageConverter;
public ResponseJsonExceptionResolver() {}
@Override
public void afterPropertiesSet() throws Exception {
if (messageConverter == null) {
messageConverter =
new MappingJackson2HttpMessageConverter(
ObjectMapperFactory.getDefaultObjectMapper());
}
}
public static String getErrorInfoFromException(Exception e) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return "\r\n" + sw.toString() + "\r\n";
} catch (Exception e2) {
return "bad getErrorInfoFromException";
}
}
@Override
protected ModelAndView doResolveException(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) {
/** web请求分页单独处理应对antd框架 */
FailData failData = new FailData();
failData.setMessage(ex.getMessage());
if (ex instanceof IgnoredException) {
IgnoredException realEx = (IgnoredException) ex;
failData.setCode(realEx.getErrorCode());
failData.setData(realEx.getData());
log.error("execute {} failed with exception", request.getRequestURL(), ex);
} else if (ex instanceof ConstraintViolationException) {
failData.setCode(ErrorCode.WRONG_PARAMETER);
failData.setMessage(getMessage((ConstraintViolationException) ex));
} else if (ex instanceof ErrorCode) {
failData.setCode(((ErrorCode) ex).getErrorCode());
} else {
log.error("execute {} failed with exception", request.getRequestURL(), ex);
}
try {
response.setCharacterEncoding("utf-8");
messageConverter.write(
failData, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return new ModelAndView();
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
public static String getMessage(ConstraintViolationException e) {
List<String> msgList = new ArrayList<>();
for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
int i = 0;
StringBuilder param = new StringBuilder();
for (Iterator<Path.Node> iterator = constraintViolation.getPropertyPath().iterator();
iterator.hasNext();
i++) {
Path.Node node = iterator.next();
if (i == 0) {
continue;
}
if (!param.toString().isBlank()) {
param.append(".");
}
param.append(node.getName());
}
msgList.add("参数 [ " + param + " ] " + constraintViolation.getMessage());
}
return StringUtils.join(msgList.toArray(), ";");
}
}

View File

@@ -0,0 +1,62 @@
package {{ .package }}.common.response;
import com.vs.common.util.rpc.pub.SuccessData;
import com.vs.ox.common.utils.ObjectMapperFactory;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.util.Collections;
/** 处理 Controller 里的返回值,从 Object转为Json */
public class ResponseJsonMethodReturnValueHandler
implements HandlerMethodReturnValueHandler, InitializingBean {
private HttpMessageConverter messageConverter;
@Override
public void afterPropertiesSet() {
if (messageConverter == null) {
messageConverter =
new MappingJackson2HttpMessageConverter(
ObjectMapperFactory.getDefaultObjectMapper());
}
}
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return true;
}
@Override
public void handleReturnValue(
Object returnValue,
MethodParameter returnType,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest)
throws Exception {
mavContainer.setRequestHandled(true);
Object result = returnValue;
/** Web分页请求的返回按照antd框架要求的格式不转为SuccessData */
result =
result == null
? new SuccessData(Collections.emptyMap())
: new SuccessData(returnValue);
ServletServerHttpResponse response =
new ServletServerHttpResponse(
webRequest.getNativeResponse(HttpServletResponse.class));
messageConverter.write(
result,
new MediaType(
MediaType.APPLICATION_JSON, Collections.singletonMap("charset", "utf-8")),
response);
}
}

View File

@@ -0,0 +1,104 @@
package {{ .package }}.common.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.method.annotation.MapMethodProcessor;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.ViewNameMethodReturnValueHandler;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Configuration
@ComponentScan("com.vs.ox")
public class WebMvcConfiguration implements WebMvcConfigurer, ApplicationContextAware {
private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
private ApplicationContext applicationContext;
// 删除 init 方法,在 setRequestMappingHandlerAdapter 中调用
private void init() {
List<HandlerMethodReturnValueHandler> returnValueHandlers =
this.requestMappingHandlerAdapter.getReturnValueHandlers();
if (returnValueHandlers == null) {
return; // 避免空指针异常
}
Iterator<HandlerMethodReturnValueHandler> iterator = returnValueHandlers.iterator();
List<HandlerMethodReturnValueHandler> newProcessors = new ArrayList<>();
while (iterator.hasNext()) {
HandlerMethodReturnValueHandler next = iterator.next();
// 为了能在controller中直接返回map不被默认的MapMethodProcessor拦截
if (next instanceof MapMethodProcessor
||
// 为了能在controller中直接返回String不被默认的ViewNameMethodReturnValueHandler拦截
next instanceof ViewNameMethodReturnValueHandler) {
continue;
} else {
newProcessors.add(next);
}
}
this.requestMappingHandlerAdapter.setReturnValueHandlers(newProcessors);
}
// 使用 configureHandlerExceptionResolvers 方法
@Override
public void configureHandlerExceptionResolvers(
List<HandlerExceptionResolver> exceptionResolvers) {
ResponseJsonExceptionResolver responseJsonExceptionResolver =
new ResponseJsonExceptionResolver();
try {
responseJsonExceptionResolver.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
}
exceptionResolvers.add(responseJsonExceptionResolver);
}
// 使用 addReturnValueHandlers 方法
@Override
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
ResponseJsonMethodReturnValueHandler responseJsonMethodReturnValueHandler =
new ResponseJsonMethodReturnValueHandler();
responseJsonMethodReturnValueHandler.afterPropertiesSet();
returnValueHandlers.add(responseJsonMethodReturnValueHandler);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Autowired private Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
ObjectMapper mapper = jackson2ObjectMapperBuilder.build();
DateFormat dateFormat = mapper.getDateFormat();
mapper.setDateFormat(new MyDateFormat(dateFormat));
MappingJackson2HttpMessageConverter mappingJsonpHttpMessageConverter =
new MappingJackson2HttpMessageConverter(mapper);
return mappingJsonpHttpMessageConverter;
}
// 删除 ServletContextListener使用 ApplicationListener 或 BeanPostProcessor
// 或者直接注入 RequestMappingHandlerAdapter
@Autowired
public void setRequestMappingHandlerAdapter(
RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
this.requestMappingHandlerAdapter = requestMappingHandlerAdapter;
init(); // 在这里调用 init 方法
}
}

View File

@@ -0,0 +1,3 @@
> 本模块存放公共工具类
``` \-- *Util.java
```