增加全功能spring-cloud-gateway,优化部分公共模块适配webFlux
This commit is contained in:
-16
@@ -1,16 +0,0 @@
|
||||
package com.central.common.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 请求的方法参数上添加该注解,则注入当前登录账号的应用id
|
||||
* 例:public void test(@LoginClient String clientId) //注入webApp
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/24 16:44
|
||||
*/
|
||||
@Target(ElementType.PARAMETER)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface LoginClient {
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package com.central.common.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 请求的方法参数SysUser上添加该注解,则注入当前登录人信息
|
||||
* 例1:public void test(@LoginUser SysUser user) //只有username 和 roles
|
||||
* 例2:public void test(@LoginUser(isFull = true) SysUser user) //能获取SysUser对象的所有信息
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/24 16:44
|
||||
*/
|
||||
@Target(ElementType.PARAMETER)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface LoginUser {
|
||||
/**
|
||||
* 是否查询SysUser对象所有信息,true则通过rpc接口查询
|
||||
*/
|
||||
boolean isFull() default false;
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package com.central.common.config;
|
||||
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import com.central.common.utils.CustomBanner;
|
||||
import com.nepxion.banner.BannerConstant;
|
||||
import com.nepxion.banner.Description;
|
||||
import com.nepxion.banner.LogoBanner;
|
||||
import com.taobao.text.Color;
|
||||
import org.springframework.context.ApplicationContextInitializer;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
|
||||
/**
|
||||
* Banner初始化
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/8/28
|
||||
*/
|
||||
public class BannerInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
|
||||
@Override
|
||||
public void initialize(ConfigurableApplicationContext applicationContext) {
|
||||
if (!(applicationContext instanceof AnnotationConfigApplicationContext)) {
|
||||
LogoBanner logoBanner = new LogoBanner(BannerInitializer.class, "/zltmp/logo.txt", "Welcome to zlt", 5, 6, new Color[5], true);
|
||||
CustomBanner.show(logoBanner, new Description(BannerConstant.VERSION + ":", CommonConstant.PROJECT_VERSION, 0, 1)
|
||||
, new Description("Gitee:", "https://gitee.com/zlt2000/microservices-platform", 0, 1)
|
||||
, new Description("Blog:", "https://blog.csdn.net/zlt2000", 0, 1)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
package com.central.common.config;
|
||||
|
||||
import com.central.common.utils.CustomThreadPoolTaskExecutor;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018/12/13
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@EnableAsync(proxyTargetClass = true)
|
||||
public class DefaultAsycTaskConfig {
|
||||
/**
|
||||
* 线程池维护线程的最小数量.
|
||||
*/
|
||||
@Value("${asyc-task.corePoolSize:10}")
|
||||
private int corePoolSize;
|
||||
/**
|
||||
* 线程池维护线程的最大数量
|
||||
*/
|
||||
@Value("${asyc-task.maxPoolSize:200}")
|
||||
private int maxPoolSize;
|
||||
/**
|
||||
* 队列最大长度
|
||||
*/
|
||||
@Value("${asyc-task.queueCapacity:10}")
|
||||
private int queueCapacity;
|
||||
/**
|
||||
* 线程池前缀
|
||||
*/
|
||||
@Value("${asyc-task.threadNamePrefix:ZltExecutor-}")
|
||||
private String threadNamePrefix;
|
||||
|
||||
@Bean
|
||||
public TaskExecutor taskExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new CustomThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(corePoolSize);
|
||||
executor.setMaxPoolSize(maxPoolSize);
|
||||
executor.setQueueCapacity(queueCapacity);
|
||||
executor.setThreadNamePrefix(threadNamePrefix);
|
||||
/*
|
||||
rejection-policy:当pool已经达到max size的时候,如何处理新任务
|
||||
CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
|
||||
*/
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package com.central.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* 密码工具类
|
||||
*/
|
||||
public class DefaultPasswordConfig {
|
||||
/**
|
||||
* 装配BCryptPasswordEncoder用户密码的匹配
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
package com.central.common.config;
|
||||
|
||||
import com.central.common.feign.UserService;
|
||||
import com.central.common.resolver.ClientArgumentResolver;
|
||||
import com.central.common.resolver.TokenArgumentResolver;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 默认SpringMVC拦截器
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/8/5
|
||||
*/
|
||||
public class DefaultWebMvcConfig extends WebMvcConfigurationSupport {
|
||||
@Lazy
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
/**
|
||||
* Token参数解析
|
||||
*
|
||||
* @param argumentResolvers 解析类
|
||||
*/
|
||||
@Override
|
||||
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
|
||||
//注入用户信息
|
||||
argumentResolvers.add(new TokenArgumentResolver(userService));
|
||||
//注入应用信息
|
||||
argumentResolvers.add(new ClientArgumentResolver());
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置资源文件目录
|
||||
* @param registry
|
||||
*/
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/**")
|
||||
.addResourceLocations("classpath:/resources/")
|
||||
.addResourceLocations("classpath:/static/")
|
||||
.addResourceLocations("classpath:/public/");
|
||||
super.addResourceHandlers(registry);
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package com.central.common.config;
|
||||
|
||||
import com.central.common.feign.UserService;
|
||||
import com.central.common.resolver.ClientArgumentResolver;
|
||||
import com.central.common.resolver.TokenArgumentResolver;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 公共配置类, 一些公共工具配置
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/8/25
|
||||
*/
|
||||
public class LoginArgResolverConfig implements WebMvcConfigurer {
|
||||
@Lazy
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
/**
|
||||
* Token参数解析
|
||||
*
|
||||
* @param argumentResolvers 解析类
|
||||
*/
|
||||
@Override
|
||||
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
|
||||
//注入用户信息
|
||||
argumentResolvers.add(new TokenArgumentResolver(userService));
|
||||
//注入应用信息
|
||||
argumentResolvers.add(new ClientArgumentResolver());
|
||||
}
|
||||
}
|
||||
-128
@@ -1,128 +0,0 @@
|
||||
package com.central.common.constant;
|
||||
|
||||
/**
|
||||
* 全局公共常量
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/10/29
|
||||
*/
|
||||
public interface CommonConstant {
|
||||
/**
|
||||
* 项目版本号(banner使用)
|
||||
*/
|
||||
String PROJECT_VERSION = "2.7.2";
|
||||
|
||||
/**
|
||||
* token请求头名称
|
||||
*/
|
||||
String TOKEN_HEADER = "Authorization";
|
||||
|
||||
/**
|
||||
* The access token issued by the authorization server. This value is REQUIRED.
|
||||
*/
|
||||
String ACCESS_TOKEN = "access_token";
|
||||
|
||||
String BEARER_TYPE = "Bearer";
|
||||
|
||||
/**
|
||||
* 标签 header key
|
||||
*/
|
||||
String HEADER_LABEL = "x-label";
|
||||
|
||||
/**
|
||||
* 标签 header 分隔符
|
||||
*/
|
||||
String HEADER_LABEL_SPLIT = ",";
|
||||
|
||||
/**
|
||||
* 标签或 名称
|
||||
*/
|
||||
String LABEL_OR = "labelOr";
|
||||
|
||||
/**
|
||||
* 标签且 名称
|
||||
*/
|
||||
String LABEL_AND = "labelAnd";
|
||||
|
||||
/**
|
||||
* 权重key
|
||||
*/
|
||||
String WEIGHT_KEY = "weight";
|
||||
|
||||
/**
|
||||
* 删除
|
||||
*/
|
||||
String STATUS_DEL = "1";
|
||||
|
||||
/**
|
||||
* 正常
|
||||
*/
|
||||
String STATUS_NORMAL = "0";
|
||||
|
||||
/**
|
||||
* 锁定
|
||||
*/
|
||||
String STATUS_LOCK = "9";
|
||||
|
||||
/**
|
||||
* 目录
|
||||
*/
|
||||
Integer CATALOG = -1;
|
||||
|
||||
/**
|
||||
* 菜单
|
||||
*/
|
||||
Integer MENU = 1;
|
||||
|
||||
/**
|
||||
* 权限
|
||||
*/
|
||||
Integer PERMISSION = 2;
|
||||
|
||||
/**
|
||||
* 删除标记
|
||||
*/
|
||||
String DEL_FLAG = "is_del";
|
||||
|
||||
/**
|
||||
* 超级管理员用户名
|
||||
*/
|
||||
String ADMIN_USER_NAME = "admin";
|
||||
|
||||
/**
|
||||
* 公共日期格式
|
||||
*/
|
||||
String MONTH_FORMAT = "yyyy-MM";
|
||||
String DATE_FORMAT = "yyyy-MM-dd";
|
||||
String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
|
||||
String SIMPLE_MONTH_FORMAT = "yyyyMM";
|
||||
String SIMPLE_DATE_FORMAT = "yyyyMMdd";
|
||||
String SIMPLE_DATETIME_FORMAT = "yyyyMMddHHmmss";
|
||||
|
||||
String DEF_USER_PASSWORD = "123456";
|
||||
|
||||
String LOCK_KEY_PREFIX = "LOCK_KEY:";
|
||||
|
||||
/**
|
||||
* 租户id参数
|
||||
*/
|
||||
String TENANT_ID_PARAM = "tenantId";
|
||||
|
||||
|
||||
/**
|
||||
* 日志链路追踪id信息头
|
||||
*/
|
||||
String TRACE_ID_HEADER = "x-traceId-header";
|
||||
/**
|
||||
* 日志链路追踪id日志标志
|
||||
*/
|
||||
String LOG_TRACE_ID = "traceId";
|
||||
/**
|
||||
* 负载均衡策略-版本号 信息头
|
||||
*/
|
||||
String Z_L_T_VERSION = "z-l-t-version";
|
||||
/**
|
||||
* 注册中心元数据 版本号
|
||||
*/
|
||||
String METADATA_VERSION = "version";
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package com.central.common.constant;
|
||||
|
||||
/**
|
||||
* 配置项常量
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/9/3
|
||||
*/
|
||||
public interface ConfigConstants {
|
||||
/**
|
||||
* 是否开启自定义隔离规则
|
||||
*/
|
||||
String CONFIG_RIBBON_ISOLATION_ENABLED = "zlt.ribbon.isolation.enabled";
|
||||
}
|
||||
-169
@@ -1,169 +0,0 @@
|
||||
package com.central.common.constant;
|
||||
|
||||
/**
|
||||
* Security 权限常量
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
public interface SecurityConstants {
|
||||
/**
|
||||
* 用户信息分隔符
|
||||
*/
|
||||
String USER_SPLIT = ":";
|
||||
|
||||
/**
|
||||
* 用户信息头
|
||||
*/
|
||||
String USER_HEADER = "x-user-header";
|
||||
|
||||
/**
|
||||
* 用户id信息头
|
||||
*/
|
||||
String USER_ID_HEADER = "x-userid-header";
|
||||
|
||||
/**
|
||||
* 角色信息头
|
||||
*/
|
||||
String ROLE_HEADER = "x-role-header";
|
||||
|
||||
/**
|
||||
* 租户信息头(应用)
|
||||
*/
|
||||
String TENANT_HEADER = "x-tenant-header";
|
||||
|
||||
/**
|
||||
* 基础角色
|
||||
*/
|
||||
String BASE_ROLE = "ROLE_USER";
|
||||
|
||||
/**
|
||||
* 授权码模式
|
||||
*/
|
||||
String AUTHORIZATION_CODE = "authorization_code";
|
||||
|
||||
/**
|
||||
* 密码模式
|
||||
*/
|
||||
String PASSWORD = "password";
|
||||
|
||||
/**
|
||||
* 刷新token
|
||||
*/
|
||||
String REFRESH_TOKEN = "refresh_token";
|
||||
|
||||
/**
|
||||
* oauth token
|
||||
*/
|
||||
String OAUTH_TOKEN_URL = "/oauth/token";
|
||||
|
||||
/**
|
||||
* 默认的处理验证码的url前缀
|
||||
*/
|
||||
String DEFAULT_VALIDATE_CODE_URL_PREFIX = "/validata/code";
|
||||
|
||||
/**
|
||||
* 手机号的处理验证码的url前缀
|
||||
*/
|
||||
String MOBILE_VALIDATE_CODE_URL_PREFIX = "/validata/smsCode";
|
||||
|
||||
/**
|
||||
* 默认生成图形验证码宽度
|
||||
*/
|
||||
String DEFAULT_IMAGE_WIDTH = "100";
|
||||
|
||||
/**
|
||||
* 默认生成图像验证码高度
|
||||
*/
|
||||
String DEFAULT_IMAGE_HEIGHT = "35";
|
||||
|
||||
/**
|
||||
* 默认生成图形验证码长度
|
||||
*/
|
||||
String DEFAULT_IMAGE_LENGTH = "4";
|
||||
|
||||
/**
|
||||
* 默认生成图形验证码过期时间
|
||||
*/
|
||||
int DEFAULT_IMAGE_EXPIRE = 60;
|
||||
|
||||
/**
|
||||
* 边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue.
|
||||
*/
|
||||
String DEFAULT_COLOR_FONT = "blue";
|
||||
|
||||
/**
|
||||
* 图片边框
|
||||
*/
|
||||
String DEFAULT_IMAGE_BORDER = "no";
|
||||
|
||||
/**
|
||||
* 默认图片间隔
|
||||
*/
|
||||
String DEFAULT_CHAR_SPACE = "5";
|
||||
|
||||
/**
|
||||
* 默认保存code的前缀
|
||||
*/
|
||||
String DEFAULT_CODE_KEY = "DEFAULT_CODE_KEY";
|
||||
|
||||
/**
|
||||
* 验证码文字大小
|
||||
*/
|
||||
String DEFAULT_IMAGE_FONT_SIZE = "30";
|
||||
/**
|
||||
* zlt公共前缀
|
||||
*/
|
||||
String ZLT_PREFIX = "zlt:";
|
||||
/**
|
||||
* 缓存client的redis key,这里是hash结构存储
|
||||
*/
|
||||
String CACHE_CLIENT_KEY = "oauth_client_details";
|
||||
/**
|
||||
* OAUTH模式登录处理地址
|
||||
*/
|
||||
String OAUTH_LOGIN_PRO_URL = "/user/login";
|
||||
/**
|
||||
* PASSWORD模式登录处理地址
|
||||
*/
|
||||
String PASSWORD_LOGIN_PRO_URL = "/oauth/user/token";
|
||||
/**
|
||||
* 获取授权码地址
|
||||
*/
|
||||
String AUTH_CODE_URL = "/oauth/authorize";
|
||||
/**
|
||||
* 登录页面
|
||||
*/
|
||||
String LOGIN_PAGE = "/login.html";
|
||||
/**
|
||||
* 默认的OPENID登录请求处理url
|
||||
*/
|
||||
String OPENID_TOKEN_URL = "/oauth/openId/token";
|
||||
/**
|
||||
* 手机登录URL
|
||||
*/
|
||||
String MOBILE_TOKEN_URL = "/oauth/mobile/token";
|
||||
/**
|
||||
* 登出URL
|
||||
*/
|
||||
String LOGOUT_URL = "/oauth/remove/token";
|
||||
/**
|
||||
* 默认token过期时间(1小时)
|
||||
*/
|
||||
Integer ACCESS_TOKEN_VALIDITY_SECONDS = 60 * 60;
|
||||
/**
|
||||
* redis中授权token对应的key
|
||||
*/
|
||||
String REDIS_TOKEN_AUTH = "auth:";
|
||||
/**
|
||||
* redis中应用对应的token集合的key
|
||||
*/
|
||||
String REDIS_CLIENT_ID_TO_ACCESS = "client_id_to_access:";
|
||||
/**
|
||||
* redis中用户名对应的token集合的key
|
||||
*/
|
||||
String REDIS_UNAME_TO_ACCESS = "uname_to_access:";
|
||||
/**
|
||||
* rsa公钥
|
||||
*/
|
||||
String RSA_PUBLIC_KEY = "pubkey.txt";
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.central.common.constant;
|
||||
|
||||
/**
|
||||
* 服务名称常量
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/27 13:50
|
||||
*/
|
||||
public interface ServiceNameConstants {
|
||||
|
||||
/**
|
||||
* 用户权限服务
|
||||
*/
|
||||
String USER_SERVICE = "user-center";
|
||||
/**
|
||||
* 搜索中心服务
|
||||
*/
|
||||
String SEARCH_SERVICE = "search-center";
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package com.central.common.context;
|
||||
|
||||
import com.alibaba.ttl.TransmittableThreadLocal;
|
||||
|
||||
/**
|
||||
* 负载均衡策略Holder
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/9/2
|
||||
*/
|
||||
public class LbIsolationContextHolder {
|
||||
private static final ThreadLocal<String> VERSION_CONTEXT = new TransmittableThreadLocal<>();
|
||||
|
||||
public static void setVersion(String version) {
|
||||
VERSION_CONTEXT.set(version);
|
||||
}
|
||||
|
||||
public static String getVersion() {
|
||||
return VERSION_CONTEXT.get();
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
VERSION_CONTEXT.remove();
|
||||
}
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
package com.central.common.context;
|
||||
|
||||
import com.alibaba.ttl.TransmittableThreadLocal;
|
||||
|
||||
/**
|
||||
* 租户holder
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/8/5
|
||||
*/
|
||||
public class TenantContextHolder {
|
||||
/**
|
||||
* 支持父子线程之间的数据传递
|
||||
*/
|
||||
private static final ThreadLocal<String> CONTEXT = new TransmittableThreadLocal<>();
|
||||
|
||||
public static void setTenant(String tenant) {
|
||||
CONTEXT.set(tenant);
|
||||
}
|
||||
|
||||
public static String getTenant() {
|
||||
return CONTEXT.get();
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
CONTEXT.remove();
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package com.central.common.exception;
|
||||
|
||||
/**
|
||||
* 业务异常
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
public class BusinessException extends RuntimeException {
|
||||
private static final long serialVersionUID = 6610083281801529147L;
|
||||
|
||||
public BusinessException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
-103
@@ -1,103 +0,0 @@
|
||||
package com.central.common.exception;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* 异常通用处理
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@ResponseBody
|
||||
@Slf4j
|
||||
public class DefaultExceptionAdvice {
|
||||
/**
|
||||
* IllegalArgumentException异常处理返回json
|
||||
* 返回状态码:400
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
@ExceptionHandler({IllegalArgumentException.class})
|
||||
public Result badRequestException(IllegalArgumentException e) {
|
||||
return defHandler("参数解析失败", e);
|
||||
}
|
||||
|
||||
/**
|
||||
* AccessDeniedException异常处理返回json
|
||||
* 返回状态码:403
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.FORBIDDEN)
|
||||
@ExceptionHandler({AccessDeniedException.class})
|
||||
public Result badMethodExpressException(AccessDeniedException e) {
|
||||
return defHandler("没有权限请求当前方法", e);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回状态码:405
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
|
||||
@ExceptionHandler({HttpRequestMethodNotSupportedException.class})
|
||||
public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
|
||||
return defHandler("不支持当前请求方法", e);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回状态码:415
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
|
||||
@ExceptionHandler({HttpMediaTypeNotSupportedException.class})
|
||||
public Result handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
|
||||
return defHandler("不支持当前媒体类型", e);
|
||||
}
|
||||
|
||||
/**
|
||||
* SQLException sql异常处理
|
||||
* 返回状态码:500
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
@ExceptionHandler({SQLException.class})
|
||||
public Result handleSQLException(SQLException e) {
|
||||
return defHandler("服务运行SQLException异常", e);
|
||||
}
|
||||
|
||||
/**
|
||||
* BusinessException 业务异常处理
|
||||
* 返回状态码:500
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public Result handleException(BusinessException e) {
|
||||
return defHandler("业务异常", e);
|
||||
}
|
||||
|
||||
/**
|
||||
* IdempotencyException 幂等性异常
|
||||
* 返回状态码:200
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ExceptionHandler(IdempotencyException.class)
|
||||
public Result handleException(IdempotencyException e) {
|
||||
return Result.failed(e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 所有异常统一处理
|
||||
* 返回状态码:500
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
@ExceptionHandler(Exception.class)
|
||||
public Result handleException(Exception e) {
|
||||
return defHandler("未知异常", e);
|
||||
}
|
||||
|
||||
private Result defHandler(String msg, Exception e) {
|
||||
log.error(msg, e);
|
||||
return Result.failed(msg);
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package com.central.common.exception;
|
||||
|
||||
/**
|
||||
* 幂等性异常
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
public class IdempotencyException extends RuntimeException {
|
||||
private static final long serialVersionUID = 6610083281801529147L;
|
||||
|
||||
public IdempotencyException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package com.central.common.exception;
|
||||
|
||||
/**
|
||||
* 分布式锁异常
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
public class LockException extends RuntimeException {
|
||||
private static final long serialVersionUID = 6610083281801529147L;
|
||||
|
||||
public LockException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
package com.central.common.feign;
|
||||
|
||||
import com.central.common.constant.ServiceNameConstants;
|
||||
import com.central.common.feign.fallback.UserServiceFallbackFactory;
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import com.central.common.model.SysUser;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = UserServiceFallbackFactory.class, decode404 = true)
|
||||
public interface UserService {
|
||||
/**
|
||||
* feign rpc访问远程/users/{username}接口
|
||||
* 查询用户实体对象SysUser
|
||||
*
|
||||
* @param username
|
||||
* @return
|
||||
*/
|
||||
@GetMapping(value = "/users/name/{username}")
|
||||
SysUser selectByUsername(@PathVariable("username") String username);
|
||||
|
||||
/**
|
||||
* feign rpc访问远程/users-anon/login接口
|
||||
*
|
||||
* @param username
|
||||
* @return
|
||||
*/
|
||||
@GetMapping(value = "/users-anon/login", params = "username")
|
||||
LoginAppUser findByUsername(@RequestParam("username") String username);
|
||||
|
||||
/**
|
||||
* 通过手机号查询用户、角色信息
|
||||
*
|
||||
* @param mobile 手机号
|
||||
*/
|
||||
@GetMapping(value = "/users-anon/mobile", params = "mobile")
|
||||
LoginAppUser findByMobile(@RequestParam("mobile") String mobile);
|
||||
|
||||
/**
|
||||
* 根据OpenId查询用户信息
|
||||
*
|
||||
* @param openId openId
|
||||
*/
|
||||
@GetMapping(value = "/users-anon/openId", params = "openId")
|
||||
LoginAppUser findByOpenId(@RequestParam("openId") String openId);
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
package com.central.common.feign.fallback;
|
||||
|
||||
import com.central.common.feign.UserService;
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import com.central.common.model.SysUser;
|
||||
import feign.hystrix.FallbackFactory;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* userService降级工场
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/1/18
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class UserServiceFallbackFactory implements FallbackFactory<UserService> {
|
||||
@Override
|
||||
public UserService create(Throwable throwable) {
|
||||
return new UserService() {
|
||||
@Override
|
||||
public SysUser selectByUsername(String username) {
|
||||
log.error("通过用户名查询用户异常:{}", username, throwable);
|
||||
return new SysUser();
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginAppUser findByUsername(String username) {
|
||||
log.error("通过用户名查询用户异常:{}", username, throwable);
|
||||
return new LoginAppUser();
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginAppUser findByMobile(String mobile) {
|
||||
log.error("通过手机号查询用户异常:{}", mobile, throwable);
|
||||
return new LoginAppUser();
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginAppUser findByOpenId(String openId) {
|
||||
log.error("通过openId查询用户异常:{}", openId, throwable);
|
||||
return new LoginAppUser();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+3
@@ -4,8 +4,10 @@ import cn.hutool.core.util.StrUtil;
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.common.context.TenantContextHolder;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -18,6 +20,7 @@ import java.io.IOException;
|
||||
* @author zlt
|
||||
* @date 2019/9/15
|
||||
*/
|
||||
@ConditionalOnClass(Filter.class)
|
||||
public class TenantFilter extends OncePerRequestFilter {
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
|
||||
+3
@@ -4,9 +4,11 @@ import cn.hutool.core.util.StrUtil;
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import com.central.log.properties.TraceProperties;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -19,6 +21,7 @@ import java.io.IOException;
|
||||
* @author zlt
|
||||
* @date 2019/9/15
|
||||
*/
|
||||
@ConditionalOnClass(Filter.class)
|
||||
public class TraceFilter extends OncePerRequestFilter {
|
||||
@Resource
|
||||
private TraceProperties traceProperties;
|
||||
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package com.central.common.lock;
|
||||
|
||||
/**
|
||||
* 分布式锁抽象类
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/5/29 14:14
|
||||
*/
|
||||
public abstract class AbstractDistributedLock implements DistributedLock{
|
||||
|
||||
@Override
|
||||
public boolean lock(String key) {
|
||||
return lock(key, TIMEOUT_MILLIS, RETRY_TIMES, SLEEP_MILLIS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean lock(String key, int retryTimes) {
|
||||
return lock(key, TIMEOUT_MILLIS, retryTimes, SLEEP_MILLIS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean lock(String key, int retryTimes, long sleepMillis) {
|
||||
return lock(key, TIMEOUT_MILLIS, retryTimes, sleepMillis);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean lock(String key, long expire) {
|
||||
return lock(key, expire, RETRY_TIMES, SLEEP_MILLIS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean lock(String key, long expire, int retryTimes) {
|
||||
return lock(key, expire, retryTimes, SLEEP_MILLIS);
|
||||
}
|
||||
}
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
package com.central.common.lock;
|
||||
|
||||
/**
|
||||
* 分布式锁顶级接口
|
||||
* 例如:
|
||||
* RETRY_TIMES=100,SLEEP_MILLIS=100
|
||||
* RETRY_TIMES * SLEEP_MILLIS = 10000 意味着如果一直获取不了锁,最长会等待10秒后抛超时异常
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/5/29 14:12
|
||||
*/
|
||||
public interface DistributedLock {
|
||||
|
||||
/**
|
||||
* 默认超时时间
|
||||
*/
|
||||
long TIMEOUT_MILLIS = 5000;
|
||||
|
||||
/**
|
||||
* 重试次数
|
||||
*/
|
||||
int RETRY_TIMES = 100;
|
||||
|
||||
/**
|
||||
* 每次重试后等待的时间
|
||||
*/
|
||||
long SLEEP_MILLIS = 100;
|
||||
|
||||
/**
|
||||
* 获取锁
|
||||
*
|
||||
* @param key key
|
||||
* @return 成功/失败
|
||||
*/
|
||||
boolean lock(String key);
|
||||
|
||||
/**
|
||||
* 获取锁
|
||||
*
|
||||
* @param key key
|
||||
* @param retryTimes 重试次数
|
||||
* @return 成功/失败
|
||||
*/
|
||||
boolean lock(String key, int retryTimes);
|
||||
|
||||
/**
|
||||
* 获取锁
|
||||
*
|
||||
* @param key key
|
||||
* @param retryTimes 重试次数
|
||||
* @param sleepMillis 获取锁失败的重试间隔
|
||||
* @return 成功/失败
|
||||
*/
|
||||
boolean lock(String key, int retryTimes, long sleepMillis);
|
||||
|
||||
/**
|
||||
* 获取锁
|
||||
*
|
||||
* @param key key
|
||||
* @param expire 获取锁超时时间
|
||||
* @return 成功/失败
|
||||
*/
|
||||
boolean lock(String key, long expire);
|
||||
|
||||
/**
|
||||
* 获取锁
|
||||
*
|
||||
* @param key key
|
||||
* @param expire 获取锁超时时间
|
||||
* @param retryTimes 重试次数
|
||||
* @return 成功/失败
|
||||
*/
|
||||
boolean lock(String key, long expire, int retryTimes);
|
||||
|
||||
/**
|
||||
* 获取锁
|
||||
*
|
||||
* @param key key
|
||||
* @param expire 获取锁超时时间
|
||||
* @param retryTimes 重试次数
|
||||
* @param sleepMillis 获取锁失败的重试间隔
|
||||
* @return 成功/失败
|
||||
*/
|
||||
boolean lock(String key, long expire, int retryTimes, long sleepMillis);
|
||||
|
||||
/**
|
||||
* 释放锁
|
||||
*
|
||||
* @param key key值
|
||||
* @return 释放结果
|
||||
*/
|
||||
boolean releaseLock(String key);
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package com.central.common.model;
|
||||
|
||||
/**
|
||||
* @Author: zlt
|
||||
*/
|
||||
public enum CodeEnum {
|
||||
SUCCESS(0),
|
||||
ERROR(1);
|
||||
|
||||
private Integer code;
|
||||
CodeEnum(Integer code){
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
package com.central.common.model;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.social.security.SocialUserDetails;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* 用户实体绑定spring security
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class LoginAppUser extends SysUser implements SocialUserDetails {
|
||||
private static final long serialVersionUID = -3685249101751401211L;
|
||||
|
||||
private Set<String> permissions;
|
||||
|
||||
/***
|
||||
* 权限重写
|
||||
*/
|
||||
@JsonIgnore
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
Collection<GrantedAuthority> collection = new HashSet<>();
|
||||
if (!CollectionUtils.isEmpty(super.getRoles())) {
|
||||
super.getRoles().parallelStream().forEach(role -> collection.add(new SimpleGrantedAuthority(role.getCode())));
|
||||
}
|
||||
return collection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return getEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUserId() {
|
||||
return getOpenId();
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.central.common.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 分页实体类
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class PageResult<T> implements Serializable {
|
||||
private static final long serialVersionUID = -275582248840137389L;
|
||||
/**
|
||||
* 总数
|
||||
*/
|
||||
private Long count;
|
||||
/**
|
||||
* 是否成功:0 成功、1 失败
|
||||
*/
|
||||
private int code;
|
||||
/**
|
||||
* 当前页结果集
|
||||
*/
|
||||
private List<T> data;
|
||||
}
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
package com.central.common.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* @Author: zlt
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Result<T> implements Serializable {
|
||||
|
||||
private T datas;
|
||||
private Integer resp_code;
|
||||
private String resp_msg;
|
||||
|
||||
public static <T> Result<T> succeed(String msg) {
|
||||
return succeedWith(null, CodeEnum.SUCCESS.getCode(), msg);
|
||||
}
|
||||
|
||||
public static <T> Result<T> succeed(T model, String msg) {
|
||||
return succeedWith(model, CodeEnum.SUCCESS.getCode(), msg);
|
||||
}
|
||||
|
||||
public static <T> Result<T> succeed(T model) {
|
||||
return succeedWith(model, CodeEnum.SUCCESS.getCode(), "");
|
||||
}
|
||||
|
||||
public static <T> Result<T> succeedWith(T datas, Integer code, String msg) {
|
||||
return new Result<>(datas, code, msg);
|
||||
}
|
||||
|
||||
public static <T> Result<T> failed(String msg) {
|
||||
return failedWith(null, CodeEnum.ERROR.getCode(), msg);
|
||||
}
|
||||
|
||||
public static <T> Result<T> failed(T model, String msg) {
|
||||
return failedWith(model, CodeEnum.ERROR.getCode(), msg);
|
||||
}
|
||||
|
||||
public static <T> Result<T> failedWith(T datas, Integer code, String msg) {
|
||||
return new Result<>(datas, code, msg);
|
||||
}
|
||||
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package com.central.common.model;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.extension.activerecord.Model;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 实体父类
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
public class SuperEntity<T extends Model<?>> extends Model<T> {
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
@TableId
|
||||
private Long id;
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private Date createTime;
|
||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||
private Date updateTime;
|
||||
|
||||
@Override
|
||||
protected Serializable pkVal() {
|
||||
return this.id;
|
||||
}
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package com.central.common.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName("sys_menu")
|
||||
public class SysMenu extends SuperEntity {
|
||||
private static final long serialVersionUID = 749360940290141180L;
|
||||
|
||||
private Long parentId;
|
||||
private String name;
|
||||
private String css;
|
||||
private String url;
|
||||
private String path;
|
||||
private Integer sort;
|
||||
private Integer type;
|
||||
private Boolean hidden;
|
||||
/**
|
||||
* 请求的类型
|
||||
*/
|
||||
private String pathMethod;
|
||||
|
||||
@TableField(exist = false)
|
||||
private List<SysMenu> subMenus;
|
||||
@TableField(exist = false)
|
||||
private Long roleId;
|
||||
@TableField(exist = false)
|
||||
private Set<Long> menuIds;
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.central.common.model;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* 角色
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName("sys_role")
|
||||
public class SysRole extends SuperEntity {
|
||||
private static final long serialVersionUID = 4497149010220586111L;
|
||||
private String code;
|
||||
private String name;
|
||||
private Long userId;
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package com.central.common.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* 用户实体
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName("sys_user")
|
||||
public class SysUser extends SuperEntity {
|
||||
private static final long serialVersionUID = -5886012896705137070L;
|
||||
|
||||
private String username;
|
||||
private String password;
|
||||
private String nickname;
|
||||
private String headImgUrl;
|
||||
private String mobile;
|
||||
private Integer sex;
|
||||
private Boolean enabled;
|
||||
private String type;
|
||||
private String openId;
|
||||
@TableLogic
|
||||
private boolean isDel;
|
||||
|
||||
@TableField(exist = false)
|
||||
private List<SysRole> roles;
|
||||
@TableField(exist = false)
|
||||
private String roleId;
|
||||
@TableField(exist = false)
|
||||
private String oldPassword;
|
||||
@TableField(exist = false)
|
||||
private String newPassword;
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package com.central.common.model;
|
||||
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* 用户类型
|
||||
*/
|
||||
public enum UserType {
|
||||
|
||||
/**
|
||||
* 前端app用户
|
||||
*/
|
||||
APP,
|
||||
/**
|
||||
* 后端管理用户
|
||||
*/
|
||||
BACKEND
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package com.central.common.properties;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 多租户配置
|
||||
* @author zlt
|
||||
* @date 2019/8/5
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@ConfigurationProperties(prefix = "zlt.tenant")
|
||||
@RefreshScope
|
||||
public class TenantProperties {
|
||||
/**
|
||||
* 是否开启多租户
|
||||
*/
|
||||
private Boolean enable = false;
|
||||
|
||||
/**
|
||||
* 配置不进行多租户隔离的表名
|
||||
*/
|
||||
private List<String> ignoreTables = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* 配置不进行多租户隔离的sql
|
||||
* 需要配置mapper的全路径如:com.central.user.mapper.SysUserMapper.findList
|
||||
*/
|
||||
private List<String> ignoreSqls = new ArrayList<>();
|
||||
}
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
package com.central.common.resolver;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.central.common.annotation.LoginClient;
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.web.bind.support.WebDataBinderFactory;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* head中的应用参数注入clientId中
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/7/10
|
||||
*/
|
||||
@Slf4j
|
||||
public class ClientArgumentResolver implements HandlerMethodArgumentResolver {
|
||||
/**
|
||||
* 入参筛选
|
||||
*
|
||||
* @param methodParameter 参数集合
|
||||
* @return 格式化后的参数
|
||||
*/
|
||||
@Override
|
||||
public boolean supportsParameter(MethodParameter methodParameter) {
|
||||
return methodParameter.hasParameterAnnotation(LoginClient.class) && methodParameter.getParameterType().equals(String.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param methodParameter 入参集合
|
||||
* @param modelAndViewContainer model 和 view
|
||||
* @param nativeWebRequest web相关
|
||||
* @param webDataBinderFactory 入参解析
|
||||
* @return 包装对象
|
||||
*/
|
||||
@Override
|
||||
public Object resolveArgument(MethodParameter methodParameter,
|
||||
ModelAndViewContainer modelAndViewContainer,
|
||||
NativeWebRequest nativeWebRequest,
|
||||
WebDataBinderFactory webDataBinderFactory) {
|
||||
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
|
||||
String clientId = request.getHeader(SecurityConstants.TENANT_HEADER);
|
||||
if (StrUtil.isBlank(clientId)) {
|
||||
log.warn("resolveArgument error clientId is empty");
|
||||
}
|
||||
return clientId;
|
||||
}
|
||||
}
|
||||
-85
@@ -1,85 +0,0 @@
|
||||
package com.central.common.resolver;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.central.common.annotation.LoginUser;
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.common.feign.UserService;
|
||||
import com.central.common.model.SysRole;
|
||||
import com.central.common.model.SysUser;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.web.bind.support.WebDataBinderFactory;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Token转化SysUser
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/12/21
|
||||
*/
|
||||
@Slf4j
|
||||
public class TokenArgumentResolver implements HandlerMethodArgumentResolver {
|
||||
private UserService userService;
|
||||
|
||||
public TokenArgumentResolver(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 入参筛选
|
||||
*
|
||||
* @param methodParameter 参数集合
|
||||
* @return 格式化后的参数
|
||||
*/
|
||||
@Override
|
||||
public boolean supportsParameter(MethodParameter methodParameter) {
|
||||
return methodParameter.hasParameterAnnotation(LoginUser.class) && methodParameter.getParameterType().equals(SysUser.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param methodParameter 入参集合
|
||||
* @param modelAndViewContainer model 和 view
|
||||
* @param nativeWebRequest web相关
|
||||
* @param webDataBinderFactory 入参解析
|
||||
* @return 包装对象
|
||||
*/
|
||||
@Override
|
||||
public Object resolveArgument(MethodParameter methodParameter,
|
||||
ModelAndViewContainer modelAndViewContainer,
|
||||
NativeWebRequest nativeWebRequest,
|
||||
WebDataBinderFactory webDataBinderFactory) {
|
||||
LoginUser loginUser = methodParameter.getParameterAnnotation(LoginUser.class);
|
||||
boolean isFull = loginUser.isFull();
|
||||
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
|
||||
String userId = request.getHeader(SecurityConstants.USER_ID_HEADER);
|
||||
String username = request.getHeader(SecurityConstants.USER_HEADER);
|
||||
String roles = request.getHeader(SecurityConstants.ROLE_HEADER);
|
||||
if (StrUtil.isBlank(username)) {
|
||||
log.warn("resolveArgument error username is empty");
|
||||
return null;
|
||||
}
|
||||
SysUser user;
|
||||
if (isFull) {
|
||||
user = userService.selectByUsername(username);
|
||||
} else {
|
||||
user = new SysUser();
|
||||
user.setId(Long.valueOf(userId));
|
||||
user.setUsername(username);
|
||||
}
|
||||
List<SysRole> sysRoleList = new ArrayList<>();
|
||||
Arrays.stream(roles.split(",")).forEach(role -> {
|
||||
SysRole sysRole = new SysRole();
|
||||
sysRole.setCode(role);
|
||||
sysRoleList.add(sysRole);
|
||||
});
|
||||
user.setRoles(sysRoleList);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
package com.central.common.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.central.common.lock.DistributedLock;
|
||||
|
||||
/**
|
||||
* service接口父类
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/1/10
|
||||
*/
|
||||
public interface ISuperService<T> extends IService<T> {
|
||||
/**
|
||||
* 幂等性新增记录
|
||||
*
|
||||
* @param entity 实体对象
|
||||
* @param lock 锁实例
|
||||
* @param lockKey 锁的key
|
||||
* @param countWrapper 判断是否存在的条件
|
||||
* @param msg 对象已存在提示信息
|
||||
* @return
|
||||
*/
|
||||
boolean saveIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper<T> countWrapper, String msg);
|
||||
|
||||
/**
|
||||
* 幂等性新增记录
|
||||
*
|
||||
* @param entity 实体对象
|
||||
* @param lock 锁实例
|
||||
* @param lockKey 锁的key
|
||||
* @param countWrapper 判断是否存在的条件
|
||||
* @return
|
||||
*/
|
||||
boolean saveIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper<T> countWrapper);
|
||||
|
||||
/**
|
||||
* 幂等性新增或更新记录
|
||||
*
|
||||
* @param entity 实体对象
|
||||
* @param lock 锁实例
|
||||
* @param lockKey 锁的key
|
||||
* @param countWrapper 判断是否存在的条件
|
||||
* @param msg 对象已存在提示信息
|
||||
* @return
|
||||
*/
|
||||
boolean saveOrUpdateIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper<T> countWrapper, String msg);
|
||||
|
||||
/**
|
||||
* 幂等性新增或更新记录
|
||||
*
|
||||
* @param entity 实体对象
|
||||
* @param lock 锁实例
|
||||
* @param lockKey 锁的key
|
||||
* @param countWrapper 判断是否存在的条件
|
||||
* @return
|
||||
*/
|
||||
boolean saveOrUpdateIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper<T> countWrapper);
|
||||
}
|
||||
-141
@@ -1,141 +0,0 @@
|
||||
package com.central.common.service.impl;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfo;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
|
||||
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
|
||||
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.central.common.exception.IdempotencyException;
|
||||
import com.central.common.exception.LockException;
|
||||
import com.central.common.lock.DistributedLock;
|
||||
import com.central.common.service.ISuperService;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* service实现父类
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/1/10
|
||||
*/
|
||||
public class SuperServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements ISuperService<T> {
|
||||
/**
|
||||
* 幂等性新增记录
|
||||
* 例子如下:
|
||||
* String username = sysUser.getUsername();
|
||||
* boolean result = super.saveIdempotency(sysUser, lock
|
||||
* , LOCK_KEY_USERNAME+username
|
||||
* , new QueryWrapper<SysUser>().eq("username", username));
|
||||
*
|
||||
* @param entity 实体对象
|
||||
* @param lock 锁实例
|
||||
* @param lockKey 锁的key
|
||||
* @param countWrapper 判断是否存在的条件
|
||||
* @param msg 对象已存在提示信息
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public boolean saveIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper<T> countWrapper, String msg) {
|
||||
if (lock == null) {
|
||||
throw new LockException("DistributedLock is null");
|
||||
}
|
||||
if (StrUtil.isEmpty(lockKey)) {
|
||||
throw new LockException("lockKey is null");
|
||||
}
|
||||
try {
|
||||
//加锁
|
||||
boolean isLock = lock.lock(lockKey);
|
||||
if (isLock) {
|
||||
//判断记录是否已存在
|
||||
int count = super.count(countWrapper);
|
||||
if (count == 0) {
|
||||
return super.save(entity);
|
||||
} else {
|
||||
if (StrUtil.isEmpty(msg)) {
|
||||
msg = "已存在";
|
||||
}
|
||||
throw new IdempotencyException(msg);
|
||||
}
|
||||
} else {
|
||||
throw new LockException("锁等待超时");
|
||||
}
|
||||
} finally {
|
||||
lock.releaseLock(lockKey);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 幂等性新增记录
|
||||
*
|
||||
* @param entity 实体对象
|
||||
* @param lock 锁实例
|
||||
* @param lockKey 锁的key
|
||||
* @param countWrapper 判断是否存在的条件
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public boolean saveIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper<T> countWrapper) {
|
||||
return saveIdempotency(entity, lock, lockKey, countWrapper, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 幂等性新增或更新记录
|
||||
* 例子如下:
|
||||
* String username = sysUser.getUsername();
|
||||
* boolean result = super.saveOrUpdateIdempotency(sysUser, lock
|
||||
* , LOCK_KEY_USERNAME+username
|
||||
* , new QueryWrapper<SysUser>().eq("username", username));
|
||||
*
|
||||
* @param entity 实体对象
|
||||
* @param lock 锁实例
|
||||
* @param lockKey 锁的key
|
||||
* @param countWrapper 判断是否存在的条件
|
||||
* @param msg 对象已存在提示信息
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public boolean saveOrUpdateIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper<T> countWrapper, String msg) {
|
||||
if (null != entity) {
|
||||
Class<?> cls = entity.getClass();
|
||||
TableInfo tableInfo = TableInfoHelper.getTableInfo(cls);
|
||||
if (null != tableInfo && StringUtils.isNotEmpty(tableInfo.getKeyProperty())) {
|
||||
Object idVal = ReflectionKit.getMethodValue(cls, entity, tableInfo.getKeyProperty());
|
||||
if (StringUtils.checkValNull(idVal) || Objects.isNull(getById((Serializable) idVal))) {
|
||||
if (StrUtil.isEmpty(msg)) {
|
||||
msg = "已存在";
|
||||
}
|
||||
return this.saveIdempotency(entity, lock, lockKey, countWrapper, msg);
|
||||
} else {
|
||||
return updateById(entity);
|
||||
}
|
||||
} else {
|
||||
throw ExceptionUtils.mpe("Error: Can not execute. Could not find @TableId.");
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 幂等性新增或更新记录
|
||||
* 例子如下:
|
||||
* String username = sysUser.getUsername();
|
||||
* boolean result = super.saveOrUpdateIdempotency(sysUser, lock
|
||||
* , LOCK_KEY_USERNAME+username
|
||||
* , new QueryWrapper<SysUser>().eq("username", username));
|
||||
*
|
||||
* @param entity 实体对象
|
||||
* @param lock 锁实例
|
||||
* @param lockKey 锁的key
|
||||
* @param countWrapper 判断是否存在的条件
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public boolean saveOrUpdateIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper<T> countWrapper) {
|
||||
return this.saveOrUpdateIdempotency(entity, lock, lockKey, countWrapper, null);
|
||||
}
|
||||
}
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2019/9/8
|
||||
*/
|
||||
@Slf4j
|
||||
public class AddrUtil {
|
||||
private final static String UNKNOWN_STR = "unknown";
|
||||
/**
|
||||
* 获取客户端IP地址
|
||||
*/
|
||||
public static String getRemoteAddr(HttpServletRequest request) {
|
||||
String ip = request.getHeader("X-Forwarded-For");
|
||||
if (isEmptyIP(ip)) {
|
||||
ip = request.getHeader("Proxy-Client-IP");
|
||||
if (isEmptyIP(ip)) {
|
||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
if (isEmptyIP(ip)) {
|
||||
ip = request.getHeader("HTTP_CLIENT_IP");
|
||||
if (isEmptyIP(ip)) {
|
||||
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
if (isEmptyIP(ip)) {
|
||||
ip = request.getRemoteAddr();
|
||||
if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
|
||||
// 根据网卡取本机配置的IP
|
||||
ip = getLocalAddr();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (ip.length() > 15) {
|
||||
String[] ips = ip.split(",");
|
||||
for (int index = 0; index < ips.length; index++) {
|
||||
String strIp = ips[index];
|
||||
if (!isEmptyIP(ip)) {
|
||||
ip = strIp;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ip;
|
||||
}
|
||||
|
||||
private static boolean isEmptyIP(String ip) {
|
||||
if (StrUtil.isEmpty(ip) || UNKNOWN_STR.equalsIgnoreCase(ip)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本机的IP地址
|
||||
*/
|
||||
public static String getLocalAddr() {
|
||||
try {
|
||||
return InetAddress.getLocalHost().getHostAddress();
|
||||
} catch (UnknownHostException e) {
|
||||
log.error("InetAddress.getLocalHost()-error", e);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import com.nepxion.banner.BannerConstant;
|
||||
import com.nepxion.banner.Description;
|
||||
import com.nepxion.banner.DescriptionBanner;
|
||||
import com.nepxion.banner.LogoBanner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2019/8/28
|
||||
*/
|
||||
public class CustomBanner {
|
||||
public static void show(LogoBanner logoBanner, Description... descriptionList) {
|
||||
String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true");
|
||||
if (!Boolean.valueOf(bannerShown)) {
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("");
|
||||
String bannerShownAnsiMode = System.getProperty(BannerConstant.BANNER_SHOWN_ANSI_MODE, "false");
|
||||
if (Boolean.valueOf(bannerShownAnsiMode)) {
|
||||
System.out.println(logoBanner.getBanner());
|
||||
} else {
|
||||
System.out.println(logoBanner.getPlainBanner());
|
||||
}
|
||||
|
||||
List<Description> descriptions = new ArrayList<>();
|
||||
for (Description description : descriptionList) {
|
||||
descriptions.add(description);
|
||||
}
|
||||
|
||||
DescriptionBanner descriptionBanner = new DescriptionBanner();
|
||||
System.out.println(descriptionBanner.getBanner(descriptions));
|
||||
}
|
||||
}
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import com.alibaba.ttl.TtlCallable;
|
||||
import com.alibaba.ttl.TtlRunnable;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.util.concurrent.ListenableFuture;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
/**
|
||||
* 这是{@link ThreadPoolTaskExecutor}的一个简单替换,可搭配TransmittableThreadLocal实现父子线程之间的数据传递
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/8/14
|
||||
*/
|
||||
public class CustomThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
|
||||
private static final long serialVersionUID = -5887035957049288777L;
|
||||
|
||||
@Override
|
||||
public void execute(Runnable runnable) {
|
||||
Runnable ttlRunnable = TtlRunnable.get(runnable);
|
||||
super.execute(ttlRunnable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Future<T> submit(Callable<T> task) {
|
||||
Callable ttlCallable = TtlCallable.get(task);
|
||||
return super.submit(ttlCallable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<?> submit(Runnable task) {
|
||||
Runnable ttlRunnable = TtlRunnable.get(task);
|
||||
return super.submit(ttlRunnable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<?> submitListenable(Runnable task) {
|
||||
Runnable ttlRunnable = TtlRunnable.get(task);
|
||||
return super.submitListenable(ttlRunnable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
|
||||
Callable ttlCallable = TtlCallable.get(task);
|
||||
return super.submitListenable(ttlCallable);
|
||||
}
|
||||
}
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import cn.afterturn.easypoi.excel.ExcelExportUtil;
|
||||
import cn.afterturn.easypoi.excel.ExcelImportUtil;
|
||||
import cn.afterturn.easypoi.excel.entity.ExportParams;
|
||||
import cn.afterturn.easypoi.excel.entity.ImportParams;
|
||||
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Excel工具类
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/1/6
|
||||
*/
|
||||
public class ExcelUtil {
|
||||
private ExcelUtil() {
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出
|
||||
*
|
||||
* @param list 数据列表
|
||||
* @param title 标题
|
||||
* @param sheetName sheet名称
|
||||
* @param pojoClass 元素类型
|
||||
* @param fileName 文件名
|
||||
* @param isCreateHeader 是否创建列头
|
||||
* @param response
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName
|
||||
, boolean isCreateHeader, HttpServletResponse response) throws IOException {
|
||||
ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
|
||||
exportParams.setCreateHeadRows(isCreateHeader);
|
||||
defaultExport(list, pojoClass, fileName, response, exportParams);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出
|
||||
*
|
||||
* @param list 数据列表
|
||||
* @param title 标题
|
||||
* @param sheetName sheet名称
|
||||
* @param pojoClass 元素类型
|
||||
* @param fileName 文件名
|
||||
* @param response
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName
|
||||
, HttpServletResponse response) throws IOException {
|
||||
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出
|
||||
*
|
||||
* @param list 数据列表(元素是Map)
|
||||
* @param fileName 文件名
|
||||
* @param response
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
|
||||
defaultExport(list, fileName, response);
|
||||
}
|
||||
|
||||
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName
|
||||
, HttpServletResponse response, ExportParams exportParams) throws IOException {
|
||||
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
|
||||
if (workbook != null) {
|
||||
downLoadExcel(fileName, response, workbook);
|
||||
}
|
||||
}
|
||||
|
||||
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
|
||||
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.XSSF);
|
||||
if (workbook != null) {
|
||||
downLoadExcel(fileName, response, workbook);
|
||||
}
|
||||
}
|
||||
|
||||
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
|
||||
workbook.write(response.getOutputStream());
|
||||
}
|
||||
|
||||
public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
|
||||
if (StringUtils.isBlank(filePath)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
ImportParams params = new ImportParams();
|
||||
params.setTitleRows(titleRows);
|
||||
params.setHeadRows(headerRows);
|
||||
return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
|
||||
}
|
||||
|
||||
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception {
|
||||
if (file == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
ImportParams params = new ImportParams();
|
||||
params.setTitleRows(titleRows);
|
||||
params.setHeadRows(headerRows);
|
||||
return ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
|
||||
}
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
/**
|
||||
* 高效分布式ID生成算法(sequence),基于Snowflake算法优化实现64位自增ID算法。
|
||||
* 其中解决时间回拨问题的优化方案如下:
|
||||
* 1. 如果发现当前时间少于上次生成id的时间(时间回拨),着计算回拨的时间差
|
||||
* 2. 如果时间差(offset)小于等于5ms,着等待 offset * 2 的时间再生成
|
||||
* 3. 如果offset大于5,则直接抛出异常
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/3/5
|
||||
*/
|
||||
public class IdGenerator {
|
||||
private static Sequence WORKER = new Sequence();
|
||||
|
||||
public static long getId() {
|
||||
return WORKER.nextId();
|
||||
}
|
||||
|
||||
public static String getIdStr() {
|
||||
return String.valueOf(WORKER.nextId());
|
||||
}
|
||||
}
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.Writer;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018/12/20
|
||||
*/
|
||||
public class ResponseUtil {
|
||||
private ResponseUtil() {
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
/**
|
||||
* 通过流写到前端
|
||||
*
|
||||
* @param objectMapper 对象序列化
|
||||
* @param response
|
||||
* @param msg 返回信息
|
||||
* @param httpStatus 返回状态码
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void responseWriter(ObjectMapper objectMapper, HttpServletResponse response, String msg, int httpStatus) throws IOException {
|
||||
Result result = Result.succeedWith(null, httpStatus, msg);
|
||||
responseWrite(objectMapper, response, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过流写到前端
|
||||
* @param objectMapper 对象序列化
|
||||
* @param response
|
||||
* @param obj
|
||||
*/
|
||||
public static void responseSucceed(ObjectMapper objectMapper, HttpServletResponse response, Object obj) throws IOException {
|
||||
Result result = Result.succeed(obj);
|
||||
responseWrite(objectMapper, response, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过流写到前端
|
||||
* @param objectMapper
|
||||
* @param response
|
||||
* @param msg
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void responseFailed(ObjectMapper objectMapper, HttpServletResponse response, String msg) throws IOException {
|
||||
Result result = Result.failed(msg);
|
||||
responseWrite(objectMapper, response, result);
|
||||
}
|
||||
|
||||
private static void responseWrite(ObjectMapper objectMapper, HttpServletResponse response, Result result) throws IOException {
|
||||
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
|
||||
try (
|
||||
Writer writer = response.getWriter()
|
||||
) {
|
||||
writer.write(objectMapper.writeValueAsString(result));
|
||||
writer.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
-117
@@ -1,117 +0,0 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import sun.misc.BASE64Decoder;
|
||||
import sun.misc.BASE64Encoder;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
|
||||
/**
|
||||
* RSA加解密工具类
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/7/16
|
||||
*/
|
||||
public class RsaUtils {
|
||||
/**
|
||||
* 默认"RSA"="RSA/ECB/PKCS1Padding"
|
||||
*/
|
||||
private static final String CIPHER_INSTANCE = "RSA/ECB/PKCS1Padding";
|
||||
|
||||
/**
|
||||
* 公钥加密
|
||||
* @param content 要加密的内容
|
||||
* @param publicKey 公钥
|
||||
*/
|
||||
public static String encrypt(String content, PublicKey publicKey) {
|
||||
try{
|
||||
Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
|
||||
byte[] output = cipher.doFinal(content.getBytes());
|
||||
BASE64Encoder encoder = new BASE64Encoder();
|
||||
return encoder.encode(output);
|
||||
}catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 公钥加密
|
||||
* @param content 要加密的内容
|
||||
* @param publicKey 公钥
|
||||
*/
|
||||
public static byte[] encrypt(byte[] content, PublicKey publicKey) {
|
||||
try{
|
||||
Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
|
||||
return cipher.doFinal(content);
|
||||
}catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 私钥解密
|
||||
* @param content 要解密的内容
|
||||
* @param privateKey 私钥
|
||||
*/
|
||||
public static byte[] decrypt(byte[] content, PrivateKey privateKey) {
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
|
||||
cipher.init(Cipher.DECRYPT_MODE, privateKey);
|
||||
return cipher.doFinal(content);
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 私钥解密
|
||||
* @param content 要解密的内容
|
||||
* @param privateKey 私钥
|
||||
*/
|
||||
public static String decrypt(String content, PrivateKey privateKey) {
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
|
||||
cipher.init(Cipher.DECRYPT_MODE, privateKey);
|
||||
byte [] b = cipher.doFinal(content.getBytes());
|
||||
BASE64Encoder encoder = new BASE64Encoder();
|
||||
return encoder.encode(b);
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* String转公钥PublicKey
|
||||
* @param key 公钥字符
|
||||
*/
|
||||
public static RSAPublicKey getPublicKey(String key) throws Exception {
|
||||
byte[] keyBytes;
|
||||
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
|
||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
return (RSAPublicKey)keyFactory.generatePublic(keySpec);
|
||||
}
|
||||
|
||||
/**
|
||||
* String转私钥PrivateKey
|
||||
* @param key 私钥字符
|
||||
*/
|
||||
public static PrivateKey getPrivateKey(String key) throws Exception {
|
||||
byte[] keyBytes;
|
||||
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
return keyFactory.generatePrivate(keySpec);
|
||||
}
|
||||
}
|
||||
-204
@@ -1,204 +0,0 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import cn.hutool.core.date.SystemClock;
|
||||
import cn.hutool.core.lang.Assert;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.core.toolkit.StringPool;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/**
|
||||
* 分布式高效有序ID生成器
|
||||
* 优化开源项目:http://git.oschina.net/yu120/sequence
|
||||
*
|
||||
* Twitter_Snowflake<br>
|
||||
* SnowFlake的结构如下(每部分用-分开):<br>
|
||||
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 -
|
||||
* 000000000000 <br>
|
||||
* 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
|
||||
* 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
|
||||
* 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T
|
||||
* = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
|
||||
* 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
|
||||
* 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br>
|
||||
* 加起来刚好64位,为一个Long型。<br>
|
||||
* SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/3/5
|
||||
*/
|
||||
@Slf4j
|
||||
public class Sequence {
|
||||
/**
|
||||
* 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
|
||||
*/
|
||||
private final long twepoch = 1288834974657L;
|
||||
/**
|
||||
* 机器标识位数
|
||||
*/
|
||||
private final long workerIdBits = 5L;
|
||||
private final long datacenterIdBits = 5L;
|
||||
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
|
||||
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
|
||||
/**
|
||||
* 毫秒内自增位
|
||||
*/
|
||||
private final long sequenceBits = 12L;
|
||||
private final long workerIdShift = sequenceBits;
|
||||
private final long datacenterIdShift = sequenceBits + workerIdBits;
|
||||
/**
|
||||
* 时间戳左移动位
|
||||
*/
|
||||
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
|
||||
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
|
||||
|
||||
private final long workerId;
|
||||
|
||||
/**
|
||||
* 数据标识 ID 部分
|
||||
*/
|
||||
private final long datacenterId;
|
||||
/**
|
||||
* 并发控制
|
||||
*/
|
||||
private long sequence = 0L;
|
||||
/**
|
||||
* 上次生产 ID 时间戳
|
||||
*/
|
||||
private long lastTimestamp = -1L;
|
||||
|
||||
/**
|
||||
* 时间回拨最长时间(ms),超过这个时间就抛出异常
|
||||
*/
|
||||
private long timestampOffset = 5L;
|
||||
|
||||
public Sequence() {
|
||||
this.datacenterId = getDatacenterId(maxDatacenterId);
|
||||
this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 有参构造器
|
||||
* </p>
|
||||
*
|
||||
* @param workerId 工作机器 ID
|
||||
* @param datacenterId 序列号
|
||||
*/
|
||||
public Sequence(long workerId, long datacenterId) {
|
||||
Assert.isFalse(workerId > maxWorkerId || workerId < 0,
|
||||
String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
|
||||
Assert.isFalse(datacenterId > maxDatacenterId || datacenterId < 0,
|
||||
String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
|
||||
this.workerId = workerId;
|
||||
this.datacenterId = datacenterId;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 获取 maxWorkerId
|
||||
* </p>
|
||||
*/
|
||||
protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
|
||||
StringBuilder mpid = new StringBuilder();
|
||||
mpid.append(datacenterId);
|
||||
String name = ManagementFactory.getRuntimeMXBean().getName();
|
||||
if (StrUtil.isNotEmpty(name)) {
|
||||
/*
|
||||
* GET jvmPid
|
||||
*/
|
||||
mpid.append(name.split(StringPool.AT)[0]);
|
||||
}
|
||||
/*
|
||||
* MAC + PID 的 hashcode 获取16个低位
|
||||
*/
|
||||
return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 数据标识id部分
|
||||
* </p>
|
||||
*/
|
||||
protected static long getDatacenterId(long maxDatacenterId) {
|
||||
long id = 0L;
|
||||
try {
|
||||
InetAddress ip = InetAddress.getLocalHost();
|
||||
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
|
||||
if (network == null) {
|
||||
id = 1L;
|
||||
} else {
|
||||
byte[] mac = network.getHardwareAddress();
|
||||
if (null != mac) {
|
||||
id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
|
||||
id = id % (maxDatacenterId + 1);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn(" getDatacenterId: " + e.getMessage());
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下一个ID
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public synchronized long nextId() {
|
||||
long timestamp = timeGen();
|
||||
//闰秒
|
||||
if (timestamp < lastTimestamp) {
|
||||
long offset = lastTimestamp - timestamp;
|
||||
if (offset <= timestampOffset) {
|
||||
try {
|
||||
wait(offset << 1);
|
||||
timestamp = timeGen();
|
||||
if (timestamp < lastTimestamp) {
|
||||
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", offset));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
} else {
|
||||
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", offset));
|
||||
}
|
||||
}
|
||||
|
||||
if (lastTimestamp == timestamp) {
|
||||
// 相同毫秒内,序列号自增
|
||||
sequence = (sequence + 1) & sequenceMask;
|
||||
if (sequence == 0) {
|
||||
// 同一毫秒的序列数已经达到最大
|
||||
timestamp = tilNextMillis(lastTimestamp);
|
||||
}
|
||||
} else {
|
||||
// 不同毫秒内,序列号置为 1 - 3 随机数
|
||||
sequence = ThreadLocalRandom.current().nextLong(1, 3);
|
||||
}
|
||||
|
||||
lastTimestamp = timestamp;
|
||||
|
||||
// 时间戳部分 | 数据中心部分 | 机器标识部分 | 序列号部分
|
||||
return ((timestamp - twepoch) << timestampLeftShift)
|
||||
| (datacenterId << datacenterIdShift)
|
||||
| (workerId << workerIdShift)
|
||||
| sequence;
|
||||
}
|
||||
|
||||
protected long tilNextMillis(long lastTimestamp) {
|
||||
long timestamp = timeGen();
|
||||
while (timestamp <= lastTimestamp) {
|
||||
timestamp = timeGen();
|
||||
}
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
protected long timeGen() {
|
||||
return SystemClock.now();
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* spring获取bean工具类
|
||||
*
|
||||
* @author 作者 owen E-mail: 624191343@qq.com
|
||||
*/
|
||||
@Component
|
||||
public class SpringUtil implements ApplicationContextAware {
|
||||
|
||||
private static ApplicationContext applicationContext = null;
|
||||
|
||||
public static <T> T getBean(Class<T> cla) {
|
||||
return applicationContext.getBean(cla);
|
||||
}
|
||||
|
||||
public static <T> T getBean(String name, Class<T> cal) {
|
||||
return applicationContext.getBean(name, cal);
|
||||
}
|
||||
|
||||
public static String getProperty(String key) {
|
||||
return applicationContext.getBean(Environment.class).getProperty(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) {
|
||||
SpringUtil.applicationContext = applicationContext;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user