spring 微服务架构--SpringBoot3.x+SpringCloudAlibaba2027+JDK17微服务基础框架搭建 - String s=String
本篇我们开始尝试搭建一套新的微服务项目
项目采用最新技术栈:SpringBoot3.2.4 + SpringCloud-2023.1+SpringCloudAlibaba-2023.0.1+JDK17
在我们实际的公司微服务项目开发过程中,通常会遇到一些底层公共组件封装问题。比如统一的请求响应封装(Resp)、统一分页请求父类(PageReq)、统一业务异常封装(BusinessException)等。Web服务公共特性封装、Redis组件公共特性封装、数据库(DAO)层的组件封装,包括模块开发规范等,这些非常考验一个架构师的整体设计能力。
本篇笔者尝试搭建 tmclcoud-base 项目作为X公司整体微服务的最底层模块。
一、项目结构
tmclcoud-base tmccloud-base-base 最底层的类库封装 (Resp 、PageReq) tmccloud-base-web Web模块公共封装(JSR303参数验证、统一异常处理) tmccloud-base-redis Redis模块封装 (统一redis序列化方式) tmccloud-base-mysql mysql数据访问层封装(mybatisplus +pagehelper分页)
后续如发现X公司有更多需要封装的底层公用组件,则可以在 tmclcoud-base 扩展子模块即可
tmclcoud-base 的pom.xml ,从全局上固定了 SpringBoot 、SpringCloud 、SpringCloudAlibaba 及 maven编译的JDK版本
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">
4.0.0
com.tingcream
tmccloud-base
pom
tmccloud-base-base
tmccloud-base-web
tmccloud-base-redis
tmccloud-base-demoweb
tmccloud-base-mysql
1.0
nexus-releases
http://192.168.31.10:8081/repository/maven-releases
nexus-snapshots
http://192.168.31.10:8081/repository/maven-snapshots
17
17
3.2.4
2023.0.1
2023.0.1.0
UTF-8
org.springframework.boot
spring-boot-dependencies
${spring-boot.version}
pom
import
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
com.alibaba.cloud
spring-cloud-alibaba-dependencies
${spring-cloud-alibaba.version}
pom
import
${project.name}
src/main/java
**/*
**/*.java
src/main/resources
**/*
**/*.java
org.springframework.boot
spring-boot-maven-plugin
${spring-boot.version}
repackage
org.apache.maven.plugins
maven-resources-plugin
3.3.1
${project.build.sourceEncoding}
org.apache.maven.plugins
maven-compiler-plugin
3.8.1
${maven.compiler.source}
${maven.compiler.target}
${project.build.sourceEncoding}
org.apache.maven.plugins
maven-source-plugin
3.2.1
attach-sources
install
jar-no-fork
二、子模块功能
1、tmccloud-base-base模块
最底层的基础类库封装,如统一响应类Resp 、统一分页请求父类PageReq 、统一业务异常等
pom.xml
org.projectlombok
lombok
cn.hutool
hutool-all
5.8.38
com.alibaba
fastjson
1.2.75
Resp.java 统一控制层响应类
package com.tingcream.tmccloud.base.core;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Resp{
/**
* 返回状态码(0操作成功 -1操作失败 9999系统异常...)
*/
private Integer code ;
/**
* 返回消息
*/
private String msg ;
/**
* 返回数据
*/
private T data;
public Resp(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Resp(Integer code, String msg,T data) {
this.code = code;
this.msg = msg;
this.data=data;
}
public staticRespsuccess(){
return new Resp(0,"操作成功") ;
}
public staticRespsuccessMsg(String msg){
return new Resp(0,msg) ;
}
public staticRespsuccess(T data){
return new Resp(0,"操作成功",data) ;
}
public staticRespfailure(){
return new Resp(-1,"操作失败") ;
}
public staticRespfailure(String msg){
return new Resp(-1,msg) ;
}
public staticRespfailure(int code ,String msg){
return new Resp(code,msg) ;
}
}
PageReq.java 统一分页请求req类需要继承的父类
package com.tingcream.tmccloud.base.core;
import lombok.Getter;
import lombok.Setter;
/**
* 分页req基类
*/
@Getter
@Setter
public class PageReq {
/**
* 当前页码(默认1)
*/
private Integer pageNum=1;
/**
* 每页条数(默认10)
*/
private Integer pageSize=10;
public PageReq() {
}
public PageReq(Integer pageNum, Integer pageSize) {
this.pageNum = pageNum;
this.pageSize = pageSize;
}
}
BusinessException.java 统一使用业务异常类
package com.tingcream.tmccloud.base.exception;
/**
* 自定义业务异常类
*/
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 4870534847958975482L;
/**
* 返回状态码 (9999系统异常)
*/
private Integer code=9999 ;
/**
* 返回状态消息
*/
private String msg;
/**
* 自定义data数据
*/
private Object data ;
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
public BusinessException(String msg) {
this.msg = msg;
}
public BusinessException(Integer code, String msg) {
this.code=code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
UuidUtil.java 基础工具(可生成8位短uuid)
package com.tingcream.tmccloud.base.util;
import java.util.UUID;
public class UuidUtil {
public static String[] chars = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
/**
* 生成短UUID(8位随机数)
* @return
*/
public static String shortUuid() {
StringBuilder builder = new StringBuilder();
String uuid = UUID.randomUUID().toString().replace("-", "");
for(int i = 0; i < 8; ++i) {
String str = uuid.substring(i * 4, i * 4 + 4);
int x = Integer.parseInt(str, 16);
builder.append(chars[x % 62]);
}
return builder.toString();
}
/**
* 生成uuid
* @return
*/
public static String uuid() {
return UUID.randomUUID().toString().replace("-", "");
}
}
2、tmccloud-base-web模块
web容器服务特性封装, 比如: 允许CORS跨域、JSR303参数验证、统一异常处理器封装等,依赖tmccloud-base-base模块。
pom.xml
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
com.tingcream
tmccloud-base
1.0
tmccloud-base-web
com.tingcream
tmccloud-base-base
${parent.version}
org.springframework.boot
spring-boot-starter-web
${spring-boot.version}
org.springframework.boot
spring-boot-starter-undertow
${spring-boot.version}
org.springframework.cloud
spring-cloud-starter-bootstrap
3.1.5
org.springframework.boot
spring-boot-starter-actuator
${spring-boot.version}
org.springframework.boot
spring-boot-starter-validation
${spring-boot.version}
org.springframework.cloud
spring-cloud-starter-openfeign
3.1.5
io.github.openfeign
feign-okhttp
11.8
org.springframework.cloud
spring-cloud-starter-loadbalancer
3.1.5
org.springframework
spring-aspects
5.3.22
cglib
cglib-nodep
3.2.10
org.apache.commons
commons-lang3
3.9
org.apache.poi
poi
4.1.2
org.apache.poi
poi-ooxml
4.1.2
org.apache.poi
poi-ooxml-schemas
4.1.2
CorsFilterConfig.java
package com.tingcream.tmccloud.baseweb.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
@Configuration
public class CorsFilterConfig {
/**
* 配置允许CORS跨域
* @return
*/
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern("*");
config.addAllowedMethod("*");
config.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE","HEAD","OPTIONS","PATCH"));
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
ValidatorConfig.java JSR303校验器配置
package com.tingcream.tmccloud.baseweb.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
/**
* JSR303 参数验证
*/
@Configuration
public class ValidatorConfig {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
}
GloalExceptionHandler.java 全局异常处理器
package com.tingcream.tmccloud.baseweb.exception;
import com.tingcream.tmccloud.base.core.Resp;
import com.tingcream.tmccloud.base.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* 全局异常处理器
*/
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
/**
* JSR303 异常
* @param e
* @param request
* @return
*/
@ExceptionHandler({BindException.class})
public Resp handleBindException(BindException e, HttpServletRequest request) {
log.error(e.getMessage());//记录完整错误信息
Listerrors = e.getBindingResult().getAllErrors();
ObjectError err= errors.get(0);
String msg = err.getDefaultMessage();
return Resp.failure(9999,msg);
}
/**
* JSR303 异常
* @param e
* @param request
* @return
*/
@ExceptionHandler({MethodArgumentNotValidException.class})
public Resp handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
log.error(e.getMessage());//记录完整错误信息
Listerrors = e.getBindingResult().getAllErrors();
ObjectError err= errors.get(0);
String msg = err.getDefaultMessage();
return Resp.failure(9999,msg);
}
/**
* JSR303 异常
* @param e
* @param request
* @return
*/
@ExceptionHandler({ConstraintViolationException.class})
public Resp handleConstraintViolationExceptionException(ConstraintViolationException e, HttpServletRequest request) {
log.error(e.getMessage());
ConstraintViolation c = (ConstraintViolation)e.getConstraintViolations().toArray()[0];
String msg =c.getMessage();
return Resp.failure(9999,msg);
}
/**
* BusinessException 自定义业务异常处理
* @param e
* @param request
* @return
*/
@ExceptionHandler({BusinessException.class})
public Resp handleBusinessException(BusinessException e, HttpServletRequest request) {
//返回自定义的状态code和msg
log.error(e.getMsg());
return new Resp<>(e.getCode(), e.getMsg(), e.getData());
}
/**
* Exception 异常
* @param e
* @param request
* @return
*/
@ExceptionHandler({Exception.class})
public Resp handleException(Exception e, HttpServletRequest request) {
log.error(e.getMessage(),e);
if(e instanceof HttpRequestMethodNotSupportedException){
return Resp.failure(9998,"客户端http请求方式有误,请检查!"); 拼多多帮助力入口
}
return Resp.failure(9997,"抱歉,服务器繁忙请稍候再试!");
}
}
3、tmccloud-base-redis模块
统一redis的序列化、反序列化方式
pom.xml
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
com.tingcream
tmccloud-base
1.0
tmccloud-base-redis
org.springframework.boot
spring-boot-starter-data-redis
MyRedisKeySerializer 自定义Redis序列化器
package com.tingcream.tmccloud.baseredis;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.io.Serializable;
import java.nio.charset.Charset;
/**
* 自定义的redis key序列化类
* key的可以为 String 、Integer、 Long 等类型
*/
public class MyRedisKeySerializer implements RedisSerializer{
private final Charset charset=Charset.forName("UTF8");
@Override
public byte[] serialize(Serializable t) throws SerializationException {
if( t instanceof String) {
String s = (String)t;
return (s == null ? null : s.getBytes(charset));
}else if( t instanceof Integer) {
String s= String.valueOf((Integer) t);
return (s == null ? null : s.getBytes(charset));
}else if( t instanceof Long) {
String s= String.valueOf((Long) t);
return (s == null ? null : s.getBytes(charset));
}else{
String s=String.valueOf(t);
return (s == null ? null : s.getBytes(charset));
}
}
@Override
public Serializable deserialize(byte[] bytes) throws SerializationException {
return (bytes == null ? null : new String(bytes, charset));
}
}
RedisHelper工具bean
package com.tingcream.tmccloud.baseredis;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* redis 辅助工具类
*/
public class RedisHelper {
//这里实际上注入的是 genericJackson2RedisTemplate 这个bean
private RedisTemplateredisTemplate;
// @Autowired
// @Qualifier("genericJackson2RedisTemplate")
// private RedisTemplateredisTemplate;
// public RedisTemplategetRedisTemplate() {
// return redisTemplate;
// }
public void setRedisTemplate( RedisTemplateredisTemplate) {
this.redisTemplate = redisTemplate;
}
public Long increment(String key){
return redisTemplate.opsForValue().increment(key, 1);
}
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
//get
public Object get( String key) {
ValueOperationsoperations = redisTemplate .opsForValue();
return operations.get(key);
}
//set
public void set( String key, Object value) {
try {
ValueOperationsoperations = redisTemplate .opsForValue();
operations.set(key, value);
} catch (Exception e) {
e.printStackTrace();
}
}
//set timeout
public void set( String key, Object value,long sec ) {
try {
ValueOperationsoperations = redisTemplate .opsForValue();
operations.set(key,value,sec, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
}
//当key不存在时写入key-value对并返回true,否则返回false
public boolean setIfAbsent(String key,Object value){
ValueOperationsoperations = redisTemplate .opsForValue();
return operations.setIfAbsent(key,value);
}
public boolean setIfAbsent(String key,Object value,long sec){
ValueOperationsoperations = redisTemplate .opsForValue();
return operations.setIfAbsent(key,value,sec,TimeUnit.SECONDS);
}
//当key存在时写入key-value并返回true,否则返回false
public boolean setIfPresent(String key,Object value){
ValueOperationsoperations = redisTemplate .opsForValue();
return operations.setIfPresent(key,value);
}
public boolean setIfPresent(String key,Object value,long sec){
ValueOperationsoperations = redisTemplate .opsForValue();
return operations.setIfPresent(key,value,sec,TimeUnit.SECONDS);
}
/**
*
* setNx set if not exist
* @param key
* @param value
* @return
*/
public void setNx(final String key,String value,Long timeout){
redisTemplate.opsForValue().set(key,value);
redisTemplate.expire(key,timeout, TimeUnit.SECONDS);
}
public void setNx(String key, String value, long timeout,TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key,value);
redisTemplate.expire(key,timeout, timeUnit);
}
public Object listLeftPop(String key){
return redisTemplate.opsForList().leftPop(key);
}
public void listRightPush(String key,Object value){
redisTemplate.opsForList().rightPush(key,value);
}
/**
* setEx set expire value
* 设置值,并同时设置key的有效期 (原子性(atomic)操作)
* @param key
* @param value
* @param secs 秒
*/
public boolean setEx(final String key, byte[] value, long secs) {
return redisTemplate.execute(new RedisCallback() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
return connection.setEx(key.getBytes(),secs,value);
}
});
}
//hget
public Object hget(String key,String field){
BoundHashOperationshashOperation= redisTemplate.boundHashOps(key);
return hashOperation.get(field);
}
//hset
public void hset(String key ,String field,Object value){
BoundHashOperationshashOperation= redisTemplate.boundHashOps(key);
hashOperation.put(field, value);
}
// hdel
public void hdel(String key,Object field){
BoundHashOperationshashOperation= redisTemplate.boundHashOps(key);
hashOperation.delete(field);
}
//hash hdel field1 field2
public void hdel(final String key,final Object... fields){
BoundHashOperationshashOperation= redisTemplate.boundHashOps(key);
hashOperation.delete(fields);
}
//hash hlen
public Long hlen(String key){
BoundHashOperationshashOperation= redisTemplate.boundHashOps(key);
return hashOperation.size();
}
// hash hkeys
public Sethkeys(String key){
BoundHashOperationshashOperation= redisTemplate.boundHashOps(key);
return hashOperation.keys();
}
// hash hvals
public List