init project v1.0.0
This commit is contained in:
@@ -0,0 +1 @@
|
||||
*.iml
|
||||
@@ -0,0 +1,23 @@
|
||||
<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>com.zlt</groupId>
|
||||
<artifactId>central-platform</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
<artifactId>zlt-commons</artifactId>
|
||||
<description>通用组件</description>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<modules>
|
||||
<module>zlt-redis-spring-boot-starter</module>
|
||||
<module>zlt-common-spring-boot-starter</module>
|
||||
<module>zlt-db-spring-boot-starter</module>
|
||||
<module>zlt-swagger2-spring-boot-starter</module>
|
||||
<module>zlt-log-spring-boot-starter</module>
|
||||
<module>zlt-ribbon-spring-boot-starter</module>
|
||||
<module>zlt-auth-client-spring-boot-starter</module>
|
||||
<module>zlt-mq-spring-boot-starter</module>
|
||||
</modules>
|
||||
</project>
|
||||
@@ -0,0 +1,2 @@
|
||||
/target/
|
||||
*.iml
|
||||
@@ -0,0 +1,39 @@
|
||||
<?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">
|
||||
<parent>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-commons</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<packaging>jar</packaging>
|
||||
<artifactId>zlt-auth-client-spring-boot-starter</artifactId>
|
||||
<description>认证客户端通用组件</description>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-common-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-oauth2</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-redis-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-context</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.central.oauth2.common.config;
|
||||
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
|
||||
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
|
||||
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
@Import(DefaultSecurityHandlerConfig.class)
|
||||
public class DefaultResourceServerConf extends ResourceServerConfigurerAdapter {
|
||||
@Autowired
|
||||
private TokenStore tokenStore;
|
||||
|
||||
@Resource
|
||||
private AuthenticationEntryPoint authenticationEntryPoint;
|
||||
|
||||
@Resource
|
||||
private OAuth2WebSecurityExpressionHandler expressionHandler;
|
||||
|
||||
@Resource
|
||||
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
|
||||
|
||||
@Autowired
|
||||
private SecurityProperties securityProperties;
|
||||
|
||||
@Override
|
||||
public void configure(ResourceServerSecurityConfigurer resources) {
|
||||
resources.tokenStore(tokenStore)
|
||||
.stateless(true)
|
||||
.authenticationEntryPoint(authenticationEntryPoint)
|
||||
.expressionHandler(expressionHandler)
|
||||
.accessDeniedHandler(oAuth2AccessDeniedHandler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity http) throws Exception {
|
||||
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl = setHttp(http)
|
||||
.authorizeRequests()
|
||||
.antMatchers(securityProperties.getIgnore().getUrls()).permitAll()
|
||||
.antMatchers(HttpMethod.OPTIONS).permitAll()
|
||||
.anyRequest();
|
||||
setAuthenticate(authorizedUrl);
|
||||
//允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
|
||||
http.headers()
|
||||
.frameOptions()
|
||||
.disable()
|
||||
.and()
|
||||
.csrf().disable();
|
||||
}
|
||||
|
||||
/**
|
||||
* url权限控制,默认是认证就通过,可以重写实现个性化
|
||||
* @param authorizedUrl
|
||||
*/
|
||||
public HttpSecurity setAuthenticate(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl) {
|
||||
return authorizedUrl.authenticated().and();
|
||||
}
|
||||
|
||||
/**
|
||||
* 留给子类重写扩展功能
|
||||
* @param http
|
||||
*/
|
||||
public HttpSecurity setHttp(HttpSecurity http) {
|
||||
return http;
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.central.oauth2.common.config;
|
||||
|
||||
import com.central.common.utils.ResponseUtil;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
|
||||
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
public class DefaultSecurityHandlerConfig {
|
||||
@Resource
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* 未登录,返回401
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public AuthenticationEntryPoint authenticationEntryPoint() {
|
||||
return (request, response, authException) -> {
|
||||
ResponseUtil.responseWriter(objectMapper, response, authException.getMessage(), HttpStatus.UNAUTHORIZED.value());
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OAuth2WebSecurityExpressionHandler oAuth2WebSecurityExpressionHandler(ApplicationContext applicationContext) {
|
||||
OAuth2WebSecurityExpressionHandler expressionHandler = new OAuth2WebSecurityExpressionHandler();
|
||||
expressionHandler.setApplicationContext(applicationContext);
|
||||
return expressionHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理spring security oauth 处理失败返回消息格式
|
||||
*/
|
||||
@Bean
|
||||
public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
|
||||
return new OAuth2AccessDeniedHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
|
||||
ResponseUtil.responseWriter(objectMapper, response, authException.getMessage(), HttpStatus.FORBIDDEN.value());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.central.oauth2.common.config;
|
||||
|
||||
import com.central.oauth2.common.store.*;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
/**
|
||||
* token存储配置
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
public class TokenStoreConfig {
|
||||
@Configuration
|
||||
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "db")
|
||||
@Import(AuthDbTokenStore.class)
|
||||
public class JdbcTokenConfig {
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "redis", matchIfMissing = true)
|
||||
@Import(AuthRedisTokenStore.class)
|
||||
public class RedisTokenConfig {
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "authJwt")
|
||||
@Import(AuthJwtTokenStore.class)
|
||||
public class AuthJwtTokenConfig {
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "resJwt")
|
||||
@Import(ResJwtTokenStore.class)
|
||||
public class ResJwtTokenConfig {
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.central.oauth2.common.constants;
|
||||
|
||||
/**
|
||||
* 权限常量
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/24 16:05
|
||||
*/
|
||||
public enum AuthoritiesEnum {
|
||||
/**
|
||||
* 管理员
|
||||
*/
|
||||
ADMIN("ROLE_ADMIN"),
|
||||
/**
|
||||
* 普通用户
|
||||
*/
|
||||
USER("ROLE_USER"),
|
||||
/**
|
||||
* 匿名用户
|
||||
*/
|
||||
ANONYMOUS("ROLE_ANONYMOUS");
|
||||
|
||||
private String role;
|
||||
|
||||
AuthoritiesEnum(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getRole() {
|
||||
return role;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.central.oauth2.common.properties;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 认证配置
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
public class AuthProperties {
|
||||
/**
|
||||
* 要认证的url
|
||||
*/
|
||||
private String[] httpUrls = {};
|
||||
|
||||
/**
|
||||
* 是否开启url权限验证
|
||||
*/
|
||||
private boolean urlEnabled = false;
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.central.oauth2.common.properties;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 配置需要放权的url白名单
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
public class PermitProperties {
|
||||
/**
|
||||
* 监控中心和swagger需要访问的url
|
||||
*/
|
||||
private static final String[] ENDPOINTS = {
|
||||
"/oauth/**",
|
||||
"/actuator/**",
|
||||
"/*/v2/api-docs",
|
||||
"/swagger/api-docs",
|
||||
"/swagger-ui.html",
|
||||
"/swagger-resources/**",
|
||||
"/webjars/**",
|
||||
"/druid/**"
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置不用认证的url
|
||||
*/
|
||||
private String[] httpUrls = {};
|
||||
|
||||
/**
|
||||
* 设置认证后不需要判断具体权限的url,所有登录的人都能访问
|
||||
*/
|
||||
private String[] menusPaths = {};
|
||||
|
||||
public String[] getUrls() {
|
||||
if (httpUrls == null || httpUrls.length == 0) {
|
||||
return ENDPOINTS;
|
||||
}
|
||||
List<String> list = new ArrayList<>();
|
||||
for (String url : ENDPOINTS) {
|
||||
list.add(url);
|
||||
}
|
||||
for (String url : httpUrls) {
|
||||
list.add(url);
|
||||
}
|
||||
return list.toArray(new String[list.size()]);
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.central.oauth2.common.properties;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2019/1/4
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@ConfigurationProperties(prefix = "zlt.security")
|
||||
@RefreshScope
|
||||
public class SecurityProperties {
|
||||
private AuthProperties auth = new AuthProperties();
|
||||
|
||||
private PermitProperties ignore = new PermitProperties();
|
||||
|
||||
private ValidateCodeProperties code = new ValidateCodeProperties();
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.central.oauth2.common.properties;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 验证码配置
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/1/4
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
public class ValidateCodeProperties {
|
||||
/**
|
||||
* 设置认证通时不需要验证码的clientId
|
||||
*/
|
||||
private String[] ignoreClientCode = {};
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.central.oauth2.common.service;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* 请求权限判断service
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/10/28
|
||||
*/
|
||||
public interface IPermissionService {
|
||||
/**
|
||||
* 判断请求是否有权限
|
||||
*
|
||||
* @param authentication 认证信息
|
||||
* @return 是否有权限
|
||||
*/
|
||||
boolean hasPermission(HttpServletRequest request, Authentication authentication);
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.central.oauth2.common.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import com.central.common.model.SysMenu;
|
||||
import com.central.common.utils.SysUserUtil;
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import com.central.oauth2.common.service.IPermissionService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 请求权限判断service
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/10/28
|
||||
*/
|
||||
@Slf4j
|
||||
public abstract class DefaultPermissionServiceImpl implements IPermissionService {
|
||||
|
||||
@Autowired
|
||||
private SecurityProperties securityProperties;
|
||||
|
||||
private AntPathMatcher antPathMatcher = new AntPathMatcher();
|
||||
|
||||
/**
|
||||
* 查询当前用户拥有的资源权限
|
||||
* @param roleCodes 角色code列表,多个以','隔开
|
||||
* @return
|
||||
*/
|
||||
public abstract List<SysMenu> findMenuByRoleCodes(String roleCodes);
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
|
||||
// 前端跨域OPTIONS请求预检放行 也可通过前端配置代理实现
|
||||
// 在这里放行具有一定风险,也可通过前端配置代理实现
|
||||
if (HttpMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod())) {
|
||||
return true;
|
||||
}
|
||||
boolean hasPermission = false;
|
||||
if (!(authentication instanceof AnonymousAuthenticationToken)) {
|
||||
//判断是否开启url权限验证
|
||||
if (!securityProperties.getAuth().isUrlEnabled()) {
|
||||
return true;
|
||||
}
|
||||
//超级管理员admin不需认证
|
||||
String username = SysUserUtil.getUsername(authentication);
|
||||
if (CommonConstant.ADMIN_USER_NAME.equals(username)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
//判断认证通过后,所以用户都能访问的url
|
||||
for (String path : securityProperties.getIgnore().getMenusPaths()) {
|
||||
if (antPathMatcher.match(path, request.getRequestURI())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
List<SimpleGrantedAuthority> grantedAuthorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
|
||||
if (CollectionUtil.isEmpty(grantedAuthorityList)) {
|
||||
log.warn("角色列表为空:{}", authentication.getPrincipal());
|
||||
return hasPermission;
|
||||
}
|
||||
|
||||
String roleCodes = grantedAuthorityList.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.joining(", "));
|
||||
List<SysMenu> menuList = findMenuByRoleCodes(roleCodes);
|
||||
for (SysMenu menu : menuList) {
|
||||
if (StringUtils.isNotEmpty(menu.getPath()) && StringUtils.isNotEmpty(menu.getPathMethod())
|
||||
&& antPathMatcher.match(menu.getPath(), request.getRequestURI())
|
||||
&& request.getMethod().equalsIgnoreCase(menu.getPathMethod())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return hasPermission;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.central.oauth2.common.store;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
/**
|
||||
* 认证服务器使用数据库存取令牌
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/24 16:23
|
||||
*/
|
||||
public class AuthDbTokenStore {
|
||||
|
||||
@Autowired
|
||||
private DataSource dataSource;
|
||||
|
||||
@Bean
|
||||
public TokenStore tokenStore(){
|
||||
return new JdbcTokenStore(dataSource);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.central.oauth2.common.store;
|
||||
|
||||
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
|
||||
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
|
||||
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.security.KeyPair;
|
||||
|
||||
/**
|
||||
* 认证服务器使用 JWT RSA 非对称加密令牌
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/24 16:21
|
||||
*/
|
||||
public class AuthJwtTokenStore {
|
||||
|
||||
@Bean("keyProp")
|
||||
public KeyProperties keyProperties() {
|
||||
return new KeyProperties();
|
||||
}
|
||||
|
||||
@Resource(name = "keyProp")
|
||||
private KeyProperties keyProperties;
|
||||
|
||||
@Bean
|
||||
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
|
||||
return new JwtTokenStore(jwtAccessTokenConverter);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtAccessTokenConverter jwtAccessTokenConverter() {
|
||||
final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
|
||||
KeyPair keyPair = new KeyStoreKeyFactory
|
||||
(keyProperties.getKeyStore().getLocation(), keyProperties.getKeyStore().getSecret().toCharArray())
|
||||
.getKeyPair(keyProperties.getKeyStore().getAlias());
|
||||
converter.setKeyPair(keyPair);
|
||||
return converter;
|
||||
}
|
||||
|
||||
/**
|
||||
* jwt 生成token 定制化处理
|
||||
* 添加一些额外的用户信息到token里面
|
||||
*
|
||||
* @return TokenEnhancer
|
||||
*/
|
||||
/*@Bean
|
||||
public TokenEnhancer tokenEnhancer() {
|
||||
return (accessToken, authentication) -> {
|
||||
final Map<String, Object> additionalInfo = new HashMap<>(1);
|
||||
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
|
||||
return accessToken;
|
||||
};
|
||||
}*/
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.central.oauth2.common.store;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
|
||||
/**
|
||||
* 认证服务器使用Redis存取令牌
|
||||
* 注意: 需要配置redis参数
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/25 9:36
|
||||
*/
|
||||
public class AuthRedisTokenStore {
|
||||
@Autowired
|
||||
private RedisTemplate<String, Object> redisTemplate ;
|
||||
|
||||
@Bean
|
||||
public TokenStore tokenStore() {
|
||||
RedisTemplateTokenStore redisTemplateStore = new RedisTemplateTokenStore() ;
|
||||
redisTemplateStore.setRedisTemplate(redisTemplate);
|
||||
return redisTemplateStore;
|
||||
}
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
package com.central.oauth2.common.store;
|
||||
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;
|
||||
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 支持redis cluster模式
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/27 11:33
|
||||
*/
|
||||
@Slf4j
|
||||
public class RedisTemplateTokenStore implements TokenStore {
|
||||
private static final String ACCESS = "access:";
|
||||
private static final String AUTH_TO_ACCESS = "auth_to_access:";
|
||||
private static final String AUTH = "auth:";
|
||||
private static final String REFRESH_AUTH = "refresh_auth:";
|
||||
private static final String ACCESS_TO_REFRESH = "access_to_refresh:";
|
||||
private static final String REFRESH = "refresh:";
|
||||
private static final String REFRESH_TO_ACCESS = "refresh_to_access:";
|
||||
private static final String CLIENT_ID_TO_ACCESS = "client_id_to_access:";
|
||||
private static final String UNAME_TO_ACCESS = "uname_to_access:";
|
||||
private static final String TOKEN = "token:";
|
||||
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();
|
||||
|
||||
public RedisTemplate<String, Object> getRedisTemplate() {
|
||||
return redisTemplate;
|
||||
}
|
||||
|
||||
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
|
||||
this.authenticationKeyGenerator = authenticationKeyGenerator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
|
||||
String key = authenticationKeyGenerator.extractKey(authentication);
|
||||
OAuth2AccessToken accessToken = (OAuth2AccessToken) redisTemplate.opsForValue().get(AUTH_TO_ACCESS + key);
|
||||
if (accessToken != null
|
||||
&& !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) {
|
||||
storeAccessToken(accessToken, authentication);
|
||||
}
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
|
||||
return readAuthentication(token.getValue());
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2Authentication readAuthentication(String token) {
|
||||
return (OAuth2Authentication) this.redisTemplate.opsForValue().get(AUTH + token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
|
||||
return readAuthenticationForRefreshToken(token.getValue());
|
||||
}
|
||||
|
||||
public OAuth2Authentication readAuthenticationForRefreshToken(String token) {
|
||||
return (OAuth2Authentication) this.redisTemplate.opsForValue().get(REFRESH_AUTH + token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
|
||||
OAuth2AccessToken existingAccessToken = this.getAccessToken(authentication);
|
||||
this.redisTemplate.opsForValue().set(ACCESS + token.getValue(), token);
|
||||
this.redisTemplate.opsForValue().set(AUTH + token.getValue(), authentication);
|
||||
this.redisTemplate.opsForValue().set(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), token);
|
||||
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("clientId", authentication.getOAuth2Request().getClientId());
|
||||
|
||||
if (authentication.getUserAuthentication() instanceof UsernamePasswordAuthenticationToken) {
|
||||
UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication.getUserAuthentication();
|
||||
LoginAppUser appUser = (LoginAppUser) authenticationToken.getPrincipal();
|
||||
params.put("username", appUser.getUsername());
|
||||
params.put("authorities", appUser.getAuthorities());
|
||||
}
|
||||
if (!params.isEmpty()) {
|
||||
this.redisTemplate.opsForValue().set(TOKEN + token.getValue(), params);
|
||||
}
|
||||
if (!authentication.isClientOnly()) {
|
||||
if (existingAccessToken != null) {
|
||||
if (!existingAccessToken.isExpired()) {
|
||||
int seconds = token.getExpiresIn();
|
||||
redisTemplate.expire(UNAME_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, TimeUnit.SECONDS);
|
||||
} else {
|
||||
redisTemplate.opsForList().rightPush(UNAME_TO_ACCESS + getApprovalKey(authentication), token);
|
||||
}
|
||||
} else {
|
||||
redisTemplate.opsForList().rightPush(UNAME_TO_ACCESS + getApprovalKey(authentication), token);
|
||||
}
|
||||
}
|
||||
|
||||
if (existingAccessToken != null) {
|
||||
if (!existingAccessToken.isExpired()) {
|
||||
int seconds = token.getExpiresIn();
|
||||
redisTemplate.expire(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, TimeUnit.SECONDS);
|
||||
} else {
|
||||
redisTemplate.opsForList().rightPush(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), token);
|
||||
}
|
||||
} else {
|
||||
redisTemplate.opsForList().rightPush(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), token);
|
||||
}
|
||||
|
||||
if (token.getExpiration() != null) {
|
||||
int seconds = token.getExpiresIn();
|
||||
redisTemplate.expire(ACCESS + token.getValue(), seconds, TimeUnit.SECONDS);
|
||||
redisTemplate.expire(AUTH + token.getValue(), seconds, TimeUnit.SECONDS);
|
||||
redisTemplate.expire(TOKEN + token.getValue(), seconds, TimeUnit.SECONDS);
|
||||
redisTemplate.expire(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), seconds, TimeUnit.SECONDS);
|
||||
redisTemplate.expire(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, TimeUnit.SECONDS);
|
||||
redisTemplate.expire(UNAME_TO_ACCESS + getApprovalKey(authentication), seconds, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
OAuth2RefreshToken refreshToken = token.getRefreshToken();
|
||||
if (refreshToken != null && refreshToken.getValue() != null) {
|
||||
this.redisTemplate.opsForValue().set(REFRESH_TO_ACCESS + token.getRefreshToken().getValue(), token.getValue());
|
||||
this.redisTemplate.opsForValue().set(ACCESS_TO_REFRESH + token.getValue(), token.getRefreshToken().getValue());
|
||||
if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
|
||||
ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
|
||||
Date expiration = expiringRefreshToken.getExpiration();
|
||||
if (expiration != null) {
|
||||
int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue();
|
||||
|
||||
redisTemplate.expire(REFRESH_TO_ACCESS + token.getRefreshToken().getValue(), seconds, TimeUnit.SECONDS);
|
||||
redisTemplate.expire(ACCESS_TO_REFRESH + token.getValue(), seconds, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String getApprovalKey(OAuth2Authentication authentication) {
|
||||
String userName = authentication.getUserAuthentication() == null ? "" : authentication.getUserAuthentication().getName();
|
||||
return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
|
||||
}
|
||||
|
||||
private String getApprovalKey(String clientId, String userName) {
|
||||
return clientId + (userName == null ? "" : ":" + userName);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void removeAccessToken(OAuth2AccessToken accessToken) {
|
||||
removeAccessToken(accessToken.getValue());
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2AccessToken readAccessToken(String tokenValue) {
|
||||
return (OAuth2AccessToken) this.redisTemplate.opsForValue().get(ACCESS + tokenValue);
|
||||
}
|
||||
|
||||
public void removeAccessToken(String tokenValue) {
|
||||
OAuth2Authentication authentication = (OAuth2Authentication) this.redisTemplate.opsForValue().get(AUTH + tokenValue);
|
||||
this.redisTemplate.delete(AUTH + tokenValue);
|
||||
redisTemplate.delete(ACCESS + tokenValue);
|
||||
redisTemplate.delete(TOKEN + tokenValue);
|
||||
this.redisTemplate.delete(ACCESS_TO_REFRESH + tokenValue);
|
||||
if (authentication != null) {
|
||||
this.redisTemplate.delete(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
|
||||
String clientId = authentication.getOAuth2Request().getClientId();
|
||||
redisTemplate.opsForList().leftPop(UNAME_TO_ACCESS + getApprovalKey(clientId, authentication.getName()));
|
||||
redisTemplate.opsForList().leftPop(CLIENT_ID_TO_ACCESS + clientId);
|
||||
this.redisTemplate.delete(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
|
||||
this.redisTemplate.opsForValue().set(REFRESH + refreshToken.getValue(), refreshToken);
|
||||
this.redisTemplate.opsForValue().set(REFRESH_AUTH + refreshToken.getValue(), authentication);
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2RefreshToken readRefreshToken(String tokenValue) {
|
||||
return (OAuth2RefreshToken) this.redisTemplate.opsForValue().get(REFRESH + tokenValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeRefreshToken(OAuth2RefreshToken refreshToken) {
|
||||
removeRefreshToken(refreshToken.getValue());
|
||||
}
|
||||
|
||||
public void removeRefreshToken(String tokenValue) {
|
||||
this.redisTemplate.delete(REFRESH + tokenValue);
|
||||
this.redisTemplate.delete(REFRESH_AUTH + tokenValue);
|
||||
this.redisTemplate.delete(REFRESH_TO_ACCESS + tokenValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
|
||||
removeAccessTokenUsingRefreshToken(refreshToken.getValue());
|
||||
}
|
||||
|
||||
private void removeAccessTokenUsingRefreshToken(String refreshToken) {
|
||||
String token = (String) this.redisTemplate.opsForValue().get(REFRESH_TO_ACCESS + refreshToken);
|
||||
if (token != null) {
|
||||
redisTemplate.delete(REFRESH_TO_ACCESS + refreshToken);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
|
||||
List<Object> result = redisTemplate.opsForList().range(UNAME_TO_ACCESS + getApprovalKey(clientId, userName), 0, -1);
|
||||
if (result == null || result.size() == 0) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(result.size());
|
||||
for (Iterator<Object> it = result.iterator(); it.hasNext(); ) {
|
||||
OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next();
|
||||
accessTokens.add(accessToken);
|
||||
}
|
||||
return Collections.unmodifiableCollection(accessTokens);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
|
||||
List<Object> result = redisTemplate.opsForList().range((CLIENT_ID_TO_ACCESS + clientId), 0, -1);
|
||||
if (result == null || result.size() == 0) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(result.size());
|
||||
for (Iterator<Object> it = result.iterator(); it.hasNext(); ) {
|
||||
OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next();
|
||||
accessTokens.add(accessToken);
|
||||
}
|
||||
return Collections.unmodifiableCollection(accessTokens);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.central.oauth2.common.store;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
|
||||
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 资源服务器 TokenStore 配置类,使用 JWT RSA 非对称加密
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/8/20 9:25
|
||||
*/
|
||||
public class ResJwtTokenStore {
|
||||
private static final String PUBLIC_KEY = "pubkey.txt";
|
||||
|
||||
@Autowired
|
||||
private ResourceServerProperties resource;
|
||||
|
||||
@Bean
|
||||
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
|
||||
return new JwtTokenStore(jwtAccessTokenConverter);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtAccessTokenConverter jwtAccessTokenConverter() {
|
||||
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
|
||||
converter.setVerifierKey(getPubKey());
|
||||
return converter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取非对称加密公钥 Key
|
||||
* @return 公钥 Key
|
||||
*/
|
||||
private String getPubKey() {
|
||||
Resource resource = new ClassPathResource(ResJwtTokenStore.PUBLIC_KEY);
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
|
||||
return br.lines().collect(Collectors.joining("\n"));
|
||||
} catch (IOException ioe) {
|
||||
return getKeyFromAuthorizationServer();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过访问授权服务器获取非对称加密公钥 Key
|
||||
* @return 公钥 Key
|
||||
*/
|
||||
private String getKeyFromAuthorizationServer() {
|
||||
if (StrUtil.isNotEmpty(this.resource.getJwt().getKeyUri())) {
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
final String username = this.resource.getClientId();
|
||||
final String password = this.resource.getClientSecret();
|
||||
if (username != null && password != null) {
|
||||
final byte[] token = Base64.getEncoder().encode((username + ":" + password).getBytes());
|
||||
headers.add("Authorization", "Basic " + new String(token));
|
||||
}
|
||||
final HttpEntity<Void> request = new HttpEntity<>(headers);
|
||||
final String url = this.resource.getJwt().getKeyUri();
|
||||
return (String) new RestTemplate()
|
||||
.exchange(url, HttpMethod.GET, request, Map.class).getBody()
|
||||
.get("value");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.central.oauth2.common.util;
|
||||
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import java.util.Enumeration;
|
||||
|
||||
/**
|
||||
* 认证授权相关工具类
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/5/13
|
||||
*/
|
||||
@Slf4j
|
||||
public class AuthUtils {
|
||||
private static final String BASIC_ = "Basic ";
|
||||
|
||||
/**
|
||||
* 获取requet(head/param)中的token
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
public static String extractToken(HttpServletRequest request) {
|
||||
String token = extractHeaderToken(request);
|
||||
if (token == null) {
|
||||
token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN);
|
||||
if (token == null) {
|
||||
log.debug("Token not found in request parameters. Not an OAuth2 request.");
|
||||
}
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析head中的token
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
private static String extractHeaderToken(HttpServletRequest request) {
|
||||
Enumeration<String> headers = request.getHeaders(CommonConstant.TOKEN_HEADER);
|
||||
while (headers.hasMoreElements()) {
|
||||
String value = headers.nextElement();
|
||||
if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
|
||||
String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
|
||||
int commaIndex = authHeaderValue.indexOf(',');
|
||||
if (commaIndex > 0) {
|
||||
authHeaderValue = authHeaderValue.substring(0, commaIndex);
|
||||
}
|
||||
return authHeaderValue;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* *从header 请求中的clientId:clientSecret
|
||||
*/
|
||||
public static String[] extractClient(HttpServletRequest request) throws IOException, UnapprovedClientAuthenticationException {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header == null || !header.startsWith(BASIC_)) {
|
||||
throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
|
||||
}
|
||||
return extractHeaderClient(header);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从header 请求中的clientId:clientSecret
|
||||
*
|
||||
* @param header header中的参数
|
||||
*/
|
||||
public static String[] extractHeaderClient(String header) throws IOException {
|
||||
byte[] base64Client = header.substring(BASIC_.length()).getBytes(CommonConstant.UTF8);
|
||||
byte[] decoded = Base64.getDecoder().decode(base64Client);
|
||||
String clientStr = new String(decoded, CommonConstant.UTF8);
|
||||
String[] clientArr = clientStr.split(":");
|
||||
if (clientArr.length != 2) {
|
||||
throw new RuntimeException("Invalid basic authentication token");
|
||||
}
|
||||
return clientArr;
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
/target/
|
||||
*.iml
|
||||
@@ -0,0 +1,72 @@
|
||||
<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>com.zlt</groupId>
|
||||
<artifactId>zlt-commons</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
<artifactId>zlt-common-spring-boot-starter</artifactId>
|
||||
<description>公共通用组件</description>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-log-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-aop</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.social</groupId>
|
||||
<artifactId>spring-social-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security.oauth</groupId>
|
||||
<artifactId>spring-security-oauth2</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-all</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<!-- easypoi -->
|
||||
<dependency>
|
||||
<groupId>cn.afterturn</groupId>
|
||||
<artifactId>easypoi-base</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.central.common.annotation;
|
||||
|
||||
import com.central.common.config.LoginArgResolverConfig;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 在启动类上添加该注解来----开启自动登录用户对象注入
|
||||
* Token转化SysUser
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Target(ElementType.TYPE)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Import(LoginArgResolverConfig.class)
|
||||
public @interface EnableLoginArgResolver {
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
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;
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.central.common.config;
|
||||
|
||||
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 ThreadPoolTaskExecutor();
|
||||
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
@@ -0,0 +1,20 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.central.common.config;
|
||||
|
||||
import com.central.common.feign.UserService;
|
||||
import com.central.common.resolver.TokenArgumentResolver;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
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 {
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
/**
|
||||
* Token参数解析
|
||||
*
|
||||
* @param argumentResolvers 解析类
|
||||
*/
|
||||
@Override
|
||||
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
|
||||
argumentResolvers.add(new TokenArgumentResolver(userService));
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package com.central.common.constant;
|
||||
|
||||
/**
|
||||
* 全局公共常量
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/10/29
|
||||
*/
|
||||
public interface CommonConstant {
|
||||
/**
|
||||
* token请求头名称
|
||||
*/
|
||||
String TOKEN_HEADER = "Authorization";
|
||||
|
||||
/**
|
||||
* 标签 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 UTF8 = "UTF-8";
|
||||
|
||||
/**
|
||||
* 超级管理员用户名
|
||||
*/
|
||||
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:";
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package com.central.common.constant;
|
||||
|
||||
/**
|
||||
* Security 权限常量
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
public interface SecurityConstants {
|
||||
/**
|
||||
* 用户信息分隔符
|
||||
*/
|
||||
String USER_SPLIT = ":";
|
||||
|
||||
/**
|
||||
* 用户信息头
|
||||
*/
|
||||
String USER_HEADER = "x-user-header";
|
||||
|
||||
/**
|
||||
* 角色信息头
|
||||
*/
|
||||
String ROLE_HEADER = "x-role-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";
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.central.common.constant;
|
||||
|
||||
/**
|
||||
* 服务名称常量
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/7/27 13:50
|
||||
*/
|
||||
public interface ServiceNameConstants {
|
||||
|
||||
/**
|
||||
* 用户权限服务
|
||||
*/
|
||||
String USER_SERVICE = "user-center";
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.central.common.exception;
|
||||
|
||||
/**
|
||||
* 业务异常
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
public class BusinessException extends RuntimeException {
|
||||
private static final long serialVersionUID = 6610083281801529147L;
|
||||
|
||||
public BusinessException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回状态码: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);
|
||||
}
|
||||
|
||||
/**
|
||||
* BusinessException 业务异常处理
|
||||
* 返回状态码:500
|
||||
*/
|
||||
@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
@@ -0,0 +1,14 @@
|
||||
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
@@ -0,0 +1,14 @@
|
||||
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
@@ -0,0 +1,51 @@
|
||||
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
@@ -0,0 +1,47 @@
|
||||
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();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
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
@@ -0,0 +1,93 @@
|
||||
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);
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
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;
|
||||
}
|
||||
|
||||
public void setCode(Integer code) {
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
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
@@ -0,0 +1,34 @@
|
||||
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;
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
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> succeedWith(T datas, Integer code, String msg) {
|
||||
return new Result<T>(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<T>(datas, code, msg);
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
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
@@ -0,0 +1,39 @@
|
||||
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;
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.central.common.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.Set;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* 权限标识
|
||||
*/
|
||||
@Data
|
||||
public class SysPermission implements Serializable {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1389727646460449239L;
|
||||
private Long id;
|
||||
private String permission;
|
||||
private String name;
|
||||
private Date createTime;
|
||||
private Date updateTime;
|
||||
|
||||
private Long roleId;
|
||||
private Set<Long> authIds;
|
||||
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
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
@@ -0,0 +1,41 @@
|
||||
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
@@ -0,0 +1,18 @@
|
||||
package com.central.common.model;
|
||||
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* 用户类型
|
||||
*/
|
||||
public enum UserType {
|
||||
|
||||
/**
|
||||
* 前端app用户
|
||||
*/
|
||||
APP,
|
||||
/**
|
||||
* 后端管理用户
|
||||
*/
|
||||
BACKEND
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
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 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.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
@@ -0,0 +1,59 @@
|
||||
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
@@ -0,0 +1,141 @@
|
||||
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.toolkit.ExceptionUtils;
|
||||
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
|
||||
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
|
||||
import com.baomidou.mybatisplus.core.toolkit.TableInfoHelper;
|
||||
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);
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 日期处理
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
public class DateUtils {
|
||||
/** 时间格式(yyyy-MM-dd) */
|
||||
public final static String DATE_PATTERN = "yyyy-MM-dd";
|
||||
/** 时间格式(yyyy-MM-dd HH:mm:ss) */
|
||||
public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
public static String format(Date date) {
|
||||
return format(date, DATE_PATTERN);
|
||||
}
|
||||
|
||||
public static String format(Date date, String pattern) {
|
||||
if(date != null){
|
||||
SimpleDateFormat df = new SimpleDateFormat(pattern);
|
||||
return df.format(date);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
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.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Excel工具类
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2019/1/6
|
||||
*/
|
||||
public class ExcelUtil {
|
||||
/**
|
||||
* 导出
|
||||
*
|
||||
* @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);
|
||||
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));
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出
|
||||
*
|
||||
* @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.setHeader("content-Type", "application/vnd.ms-excel");
|
||||
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 null;
|
||||
}
|
||||
ImportParams params = new ImportParams();
|
||||
params.setTitleRows(titleRows);
|
||||
params.setHeadRows(headerRows);
|
||||
List<T> list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception {
|
||||
if (file == null) {
|
||||
return null;
|
||||
}
|
||||
ImportParams params = new ImportParams();
|
||||
params.setTitleRows(titleRows);
|
||||
params.setHeadRows(headerRows);
|
||||
List<T> list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* 正则表达式手机号码校验类
|
||||
*/
|
||||
public class PhoneUtil {
|
||||
private static String REGEX = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
|
||||
private static Pattern P = Pattern.compile(REGEX);
|
||||
|
||||
/**
|
||||
* 校验手机号
|
||||
*
|
||||
* @param phone
|
||||
* @return
|
||||
*/
|
||||
public static boolean checkPhone(String phone) {
|
||||
if (phone == null || phone.length() != 11) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
|
||||
Matcher m = P.matcher(phone);
|
||||
return m.matches();
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.Writer;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018/12/20
|
||||
*/
|
||||
public class ResponseUtil {
|
||||
/**
|
||||
* 通过流写到前端
|
||||
*
|
||||
* @param objectMapper 对象序列化
|
||||
* @param response
|
||||
* @param msg 返回信息
|
||||
* @param httpStatus 返回状态码
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void responseWriter(ObjectMapper objectMapper, HttpServletResponse response, String msg, int httpStatus) throws IOException {
|
||||
Map<String, String> rsp = new HashMap<>(2);
|
||||
response.setStatus(httpStatus);
|
||||
rsp.put("resp_code", String.valueOf(httpStatus));
|
||||
rsp.put("resp_msg", msg);
|
||||
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
|
||||
try (
|
||||
Writer writer = response.getWriter()
|
||||
) {
|
||||
writer.write(objectMapper.writeValueAsString(rsp));
|
||||
writer.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* spring获取bean工具类
|
||||
* @author zlt
|
||||
*/
|
||||
@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) throws BeansException {
|
||||
SpringUtil.applicationContext = applicationContext;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import com.central.common.model.SysRole;
|
||||
import com.central.common.model.SysUser;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
|
||||
|
||||
import com.central.common.model.LoginAppUser;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 获取用户信息
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
public class SysUserUtil {
|
||||
public static LoginAppUser getLoginAppUser(SysUser user) {
|
||||
LoginAppUser login = new LoginAppUser();
|
||||
BeanUtil.copyProperties(user, login);
|
||||
return login;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取登陆的用户名
|
||||
*/
|
||||
public static String getUsername(Authentication authentication) {
|
||||
Object principal = authentication.getPrincipal();
|
||||
String username = null;
|
||||
if (principal instanceof SysUser) {
|
||||
username = ((SysUser) principal).getUsername();
|
||||
} else if (principal instanceof String) {
|
||||
username = (String) principal;
|
||||
}
|
||||
return username;
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 短8位UUID思想其实借鉴微博短域名的生成方式,但是其重复概率过高,而且每次生成4个,需要随即选取一个。
|
||||
*
|
||||
* 本算法利用62个可打印字符,通过随机生成32位UUID,由于UUID都为十六进制,所以将UUID分成8组,每4个为一组,然后通过模62操作,
|
||||
* 结果作为索引取出字符, 这样重复率大大降低。
|
||||
*
|
||||
* 经测试,在生成一千万个数据也没有出现重复,完全满足大部分需求。
|
||||
*
|
||||
* @author wangfan
|
||||
* @date 2017-3-28 下午1:11:31
|
||||
*/
|
||||
public class UUIDUtil {
|
||||
private 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" };
|
||||
|
||||
/**
|
||||
* 生成8位uuid
|
||||
* @return
|
||||
* @author wangfan
|
||||
*/
|
||||
public static String randomUUID8() {
|
||||
StringBuffer shortBuffer = new StringBuffer();
|
||||
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);
|
||||
shortBuffer.append(chars[x % 0x3E]);
|
||||
}
|
||||
return shortBuffer.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成32位uuid
|
||||
* @return
|
||||
* @author wangfan
|
||||
*/
|
||||
public static String randomUUID32(){
|
||||
String uuid = UUID.randomUUID().toString().replace("-", "");
|
||||
return uuid;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
/target/
|
||||
*.iml
|
||||
@@ -0,0 +1,25 @@
|
||||
<?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">
|
||||
<parent>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-commons</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<packaging>jar</packaging>
|
||||
<artifactId>zlt-db-spring-boot-starter</artifactId>
|
||||
<description>数据库通用组件</description>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<!-- druid 官方 starter -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.central.db.config;
|
||||
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 自定义填充公共 name 字段
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/12/11
|
||||
*/
|
||||
public class DateMetaObjectHandler implements MetaObjectHandler {
|
||||
|
||||
/**
|
||||
* 插入填充,字段为空自动填充
|
||||
*/
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
Object createTime = getFieldValByName("createTime", metaObject);
|
||||
Object updateTime = getFieldValByName("updateTime", metaObject);
|
||||
if (createTime == null || updateTime == null) {
|
||||
Date date = new Date();
|
||||
if (createTime == null) {
|
||||
setFieldValByName("createTime", date, metaObject);
|
||||
}
|
||||
if (updateTime == null) {
|
||||
setFieldValByName("updateTime", date, metaObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新填充
|
||||
*
|
||||
* @param metaObject
|
||||
*/
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
//mybatis-plus版本2.0.9+
|
||||
setFieldValByName("updateTime", new Date(), metaObject);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.central.db.config;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
/**
|
||||
* mybatis-plus配置
|
||||
* @author zlt
|
||||
* @date 2018/12/13
|
||||
*/
|
||||
@Import(DateMetaObjectHandler.class)
|
||||
public class DefaultMybatisPlusConfig {
|
||||
/**
|
||||
* 分页插件,自动识别数据库类型
|
||||
*/
|
||||
@Bean
|
||||
public PaginationInterceptor paginationInterceptor() {
|
||||
return new PaginationInterceptor();
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印 sql,性能分析拦截器,不建议生产使用
|
||||
* 设置 dev test 环境开启
|
||||
*/
|
||||
@Bean
|
||||
@Profile({"dev","test"})
|
||||
public PerformanceInterceptor performanceInterceptor() {
|
||||
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
|
||||
return performanceInterceptor;
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.central.db.mapper;
|
||||
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
|
||||
/**
|
||||
* mapper 父类,注意这个类不要让 mp 扫描到!!
|
||||
* @author zlt
|
||||
*/
|
||||
public interface SuperMapper<T> extends BaseMapper<T> {
|
||||
// 这里可以放一些公共的方法
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
/target/
|
||||
*.iml
|
||||
@@ -0,0 +1,21 @@
|
||||
<?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">
|
||||
<parent>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-commons</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<packaging>jar</packaging>
|
||||
<artifactId>zlt-log-spring-boot-starter</artifactId>
|
||||
<description>日志通用组件</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.central.log.monitor;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* 日志埋点工具类
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Slf4j
|
||||
public class PointUtil {
|
||||
public static final String SPLIT = "|";
|
||||
|
||||
/**
|
||||
* 格式为:{时间}|{来源}|{对象id}|{类型}|{对象属性(以&分割)}
|
||||
* 例子1:2016-07-27 23:37:23|business-center|1|user-login|ip=xxx.xxx.xx&userName=张三&userType=后台管理员
|
||||
* 例子2:2016-07-27 23:37:23|file-center|c0a895e114526786450161001d1ed9|file-upload|fileName=xxx&filePath=xxx
|
||||
*
|
||||
* @param id 对象id
|
||||
* @param type 类型
|
||||
* @param message 对象属性
|
||||
*/
|
||||
public static void info(String id, String type, String message) {
|
||||
log.info(id + SPLIT + type + SPLIT + message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<contextName>${APP_NAME}</contextName>
|
||||
<springProperty name="APP_NAME" scope="context" source="spring.application.name"/>
|
||||
<springProperty name="LOG_FILE" scope="context" source="logging.file" defaultValue="../logs/application/${APP_NAME}"/>
|
||||
<springProperty name="LOG_POINT_FILE" scope="context" source="logging.file" defaultValue="logs/point"/>
|
||||
<springProperty name="LOG_MAXFILESIZE" scope="context" source="logback.filesize" defaultValue="50MB"/>
|
||||
<springProperty name="LOG_FILEMAXDAY" scope="context" source="logback.filemaxday" defaultValue="7"/>
|
||||
<springProperty name="ServerIP" scope="context" source="spring.cloud.client.ip-address" defaultValue="0.0.0.0"/>
|
||||
<springProperty name="ServerPort" scope="context" source="server.port" defaultValue="0000"/>
|
||||
|
||||
<!-- 彩色日志 -->
|
||||
<!-- 彩色日志依赖的渲染类 -->
|
||||
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
|
||||
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
|
||||
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
|
||||
|
||||
<!-- 彩色日志格式 -->
|
||||
<property name="CONSOLE_LOG_PATTERN"
|
||||
value="[${APP_NAME}:${ServerIP}:${ServerPort}] %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%level){blue} %clr(${PID}){magenta} %clr([%thread]){orange} %clr(%logger){cyan} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}" />
|
||||
<property name="CONSOLE_LOG_PATTERN_NO_COLOR" value="[${APP_NAME}:${ServerIP}:${ServerPort}] %d{yyyy-MM-dd HH:mm:ss.SSS} %level ${PID} [%thread] %logger %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}" />
|
||||
|
||||
<!-- 控制台日志 -->
|
||||
<appender name="StdoutAppender" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<withJansi>true</withJansi>
|
||||
<encoder>
|
||||
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
|
||||
<charset>UTF-8</charset>
|
||||
</encoder>
|
||||
</appender>
|
||||
<!-- 按照每天生成常规日志文件 -->
|
||||
<appender name="FileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_FILE}/${APP_NAME}.log</file>
|
||||
<encoder>
|
||||
<pattern>${CONSOLE_LOG_PATTERN_NO_COLOR}</pattern>
|
||||
<charset>UTF-8</charset>
|
||||
</encoder>
|
||||
<!-- 基于时间的分包策略 -->
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_FILE}/${APP_NAME}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
|
||||
<!--保留时间,单位:天-->
|
||||
<maxHistory>${LOG_FILEMAXDAY}</maxHistory>
|
||||
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
|
||||
<maxFileSize>${LOG_MAXFILESIZE}</maxFileSize>
|
||||
</timeBasedFileNamingAndTriggeringPolicy>
|
||||
</rollingPolicy>
|
||||
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
||||
<level>INFO</level>
|
||||
</filter>
|
||||
</appender>
|
||||
|
||||
<appender name="point_log" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_POINT_FILE}/point.log</file>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss}|${APP_NAME}|%msg%n</pattern>
|
||||
<charset>UTF-8</charset>
|
||||
</encoder>
|
||||
<!-- 基于时间的分包策略 -->
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_POINT_FILE}/point.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
|
||||
<!--保留时间,单位:天-->
|
||||
<maxHistory>${LOG_FILEMAXDAY}</maxHistory>
|
||||
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
|
||||
<maxFileSize>${LOG_MAXFILESIZE}</maxFileSize>
|
||||
</timeBasedFileNamingAndTriggeringPolicy>
|
||||
</rollingPolicy>
|
||||
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
||||
<level>INFO</level>
|
||||
</filter>
|
||||
</appender>
|
||||
|
||||
<appender name="point_log_async" class="ch.qos.logback.classic.AsyncAppender">
|
||||
<discardingThreshold>0</discardingThreshold>
|
||||
<appender-ref ref="point_log"/>
|
||||
</appender>
|
||||
<logger name="com.central.log.monitor" level="info" addtivity="false">
|
||||
<appender-ref ref="point_log_async" />
|
||||
</logger>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="StdoutAppender"/>
|
||||
<appender-ref ref="FileAppender"/>
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,2 @@
|
||||
/target/
|
||||
*.iml
|
||||
@@ -0,0 +1,11 @@
|
||||
<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">
|
||||
<parent>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-commons</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>zlt-mq-spring-boot-starter</artifactId>
|
||||
<description>消息队列通用组件</description>
|
||||
<packaging>jar</packaging>
|
||||
</project>
|
||||
@@ -0,0 +1,2 @@
|
||||
/target/
|
||||
*.iml
|
||||
@@ -0,0 +1,53 @@
|
||||
<?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">
|
||||
<parent>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-commons</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<packaging>jar</packaging>
|
||||
<artifactId>zlt-redis-spring-boot-starter</artifactId>
|
||||
<description>redis通用组件</description>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-common-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>redis.clients</groupId>
|
||||
<artifactId>jedis</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<artifactId>lettuce-core</artifactId>
|
||||
<groupId>io.lettuce</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<!-- jedis客户端 -->
|
||||
<dependency>
|
||||
<groupId>redis.clients</groupId>
|
||||
<artifactId>jedis</artifactId>
|
||||
</dependency>
|
||||
<!-- spring2.X集成redis所需common-pool2,使用jedis必须依赖它-->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-pool2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package com.central.common.redis;
|
||||
|
||||
import com.central.common.redis.properties.CacheManagerProperties;
|
||||
import com.central.common.redis.template.RedisRepository;
|
||||
import com.central.common.redis.util.RedisObjectSerializer;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.interceptor.KeyGenerator;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.data.redis.cache.RedisCacheConfiguration;
|
||||
import org.springframework.data.redis.cache.RedisCacheManager;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.*;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* redis 配置类
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/11/6 11:02
|
||||
*/
|
||||
@Configuration
|
||||
@ConditionalOnClass(RedisRepository.class)
|
||||
@EnableConfigurationProperties({RedisProperties.class, CacheManagerProperties.class})
|
||||
@EnableCaching
|
||||
public class RedisAutoConfigure {
|
||||
@Autowired
|
||||
private CacheManagerProperties cacheManagerProperties;
|
||||
|
||||
/**
|
||||
* RedisTemplate配置
|
||||
* @param factory
|
||||
*/
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
|
||||
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
|
||||
redisTemplate.setConnectionFactory(factory);
|
||||
|
||||
RedisSerializer stringSerializer = new StringRedisSerializer();
|
||||
RedisSerializer redisObjectSerializer = new RedisObjectSerializer();
|
||||
redisTemplate.setKeySerializer(stringSerializer);
|
||||
redisTemplate.setHashKeySerializer(stringSerializer);
|
||||
redisTemplate.setValueSerializer(redisObjectSerializer);
|
||||
redisTemplate.afterPropertiesSet();
|
||||
return redisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redis repository redis repository.
|
||||
*
|
||||
* @param redisTemplate the redis template
|
||||
* @return the redis repository
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public RedisRepository redisRepository(RedisTemplate<String, Object> redisTemplate) {
|
||||
return new RedisRepository(redisTemplate);
|
||||
}
|
||||
|
||||
@Bean(name = "cacheManager")
|
||||
@Primary
|
||||
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
|
||||
RedisCacheConfiguration difConf = getDefConf().entryTtl(Duration.ofHours(1));
|
||||
|
||||
//自定义的缓存过期时间配置
|
||||
int configSize = cacheManagerProperties.getConfigs() == null ? 0 : cacheManagerProperties.getConfigs().size();
|
||||
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>(configSize);
|
||||
if (configSize > 0) {
|
||||
cacheManagerProperties.getConfigs().forEach(e -> {
|
||||
RedisCacheConfiguration conf = getDefConf().entryTtl(Duration.ofSeconds(e.getSecond()));
|
||||
redisCacheConfigurationMap.put(e.getKey(), conf);
|
||||
});
|
||||
}
|
||||
|
||||
return RedisCacheManager.builder(redisConnectionFactory)
|
||||
.cacheDefaults(difConf)
|
||||
.withInitialCacheConfigurations(redisCacheConfigurationMap)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public KeyGenerator keyGenerator() {
|
||||
return (target, method, objects) -> {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(target.getClass().getName());
|
||||
sb.append(":" + method.getName() + ":");
|
||||
for (Object obj : objects) {
|
||||
sb.append(obj.toString());
|
||||
}
|
||||
return sb.toString();
|
||||
};
|
||||
}
|
||||
|
||||
private RedisCacheConfiguration getDefConf() {
|
||||
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
|
||||
.disableCachingNullValues()
|
||||
.computePrefixWith(cacheName -> "cache".concat(":").concat(cacheName).concat(":"))
|
||||
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
|
||||
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new RedisObjectSerializer()));
|
||||
return cacheConfiguration;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.central.common.redis.constant;
|
||||
|
||||
/**
|
||||
* redis 工具常量
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/5/21 11:59
|
||||
*/
|
||||
public class RedisToolsConstant {
|
||||
|
||||
/**
|
||||
* single Redis
|
||||
*/
|
||||
public final static int SINGLE = 1 ;
|
||||
|
||||
/**
|
||||
* Redis cluster
|
||||
*/
|
||||
public final static int CLUSTER = 2 ;
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.central.common.redis.lock;
|
||||
|
||||
import com.central.common.lock.AbstractDistributedLock;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.RedisCallback;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisCluster;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* redis分布式锁实现
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/5/29 14:16
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class RedisDistributedLock extends AbstractDistributedLock {
|
||||
@Autowired
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
private ThreadLocal<String> lockFlag = new ThreadLocal<>();
|
||||
|
||||
private static final String UNLOCK_LUA;
|
||||
|
||||
/*
|
||||
* 通过lua脚本释放锁,来达到释放锁的原子操作
|
||||
*/
|
||||
static {
|
||||
UNLOCK_LUA = "if redis.call(\"get\",KEYS[1]) == ARGV[1] " +
|
||||
"then " +
|
||||
" return redis.call(\"del\",KEYS[1]) " +
|
||||
"else " +
|
||||
" return 0 " +
|
||||
"end ";
|
||||
}
|
||||
|
||||
public RedisDistributedLock(RedisTemplate<String, Object> redisTemplate) {
|
||||
super();
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean lock(String key, long expire, int retryTimes, long sleepMillis) {
|
||||
boolean result = setRedis(key, expire);
|
||||
// 如果获取锁失败,按照传入的重试次数进行重试
|
||||
while ((!result) && retryTimes-- > 0) {
|
||||
try {
|
||||
log.debug("get redisDistributeLock failed, retrying..." + retryTimes);
|
||||
Thread.sleep(sleepMillis);
|
||||
} catch (InterruptedException e) {
|
||||
return false;
|
||||
}
|
||||
result = setRedis(key, expire);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean setRedis(final String key, final long expire) {
|
||||
try {
|
||||
String status = redisTemplate.execute((RedisCallback<String>) connection -> {
|
||||
Object nativeConnection = connection.getNativeConnection();
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
lockFlag.set(uuid);
|
||||
String result = null;
|
||||
// 集群模式和单机模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行
|
||||
// 集群模式
|
||||
if (nativeConnection instanceof JedisCluster) {
|
||||
result = ((JedisCluster) nativeConnection).set(key, uuid, "NX", "PX", expire);
|
||||
}
|
||||
// 单机模式
|
||||
else if (nativeConnection instanceof Jedis) {
|
||||
result = ((Jedis) nativeConnection).set(key, uuid, "NX", "PX", expire);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
return !StringUtils.isEmpty(status);
|
||||
} catch (Exception e) {
|
||||
log.error("set redisDistributeLock occured an exception", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean releaseLock(String key) {
|
||||
// 释放锁的时候,有可能因为持锁之后方法执行时间大于锁的有效期,此时有可能已经被另外一个线程持有锁,所以不能直接删除
|
||||
try {
|
||||
final List<String> keys = new ArrayList<>();
|
||||
keys.add(key);
|
||||
final List<String> args = new ArrayList<>();
|
||||
args.add(lockFlag.get());
|
||||
|
||||
// 使用lua脚本删除redis中匹配value的key,可以避免由于方法执行时间过长而redis锁自动过期失效的时候误删其他线程的锁
|
||||
// spring自带的执行脚本方法中,集群模式直接抛出不支持执行脚本的异常,所以只能拿到原redis的connection来执行脚本
|
||||
|
||||
Long result = redisTemplate.execute((RedisCallback<Long>) connection -> {
|
||||
Object nativeConnection = connection.getNativeConnection();
|
||||
// 集群模式和单机模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行
|
||||
// 集群模式
|
||||
if (nativeConnection instanceof JedisCluster) {
|
||||
return (Long) ((JedisCluster) nativeConnection).eval(UNLOCK_LUA, keys, args);
|
||||
}
|
||||
|
||||
// 单机模式
|
||||
else if (nativeConnection instanceof Jedis) {
|
||||
return (Long) ((Jedis) nativeConnection).eval(UNLOCK_LUA, keys, args);
|
||||
}
|
||||
return 0L;
|
||||
});
|
||||
|
||||
return result != null && result > 0;
|
||||
} catch (Exception e) {
|
||||
log.error("release redisDistributeLock occured an exception", e);
|
||||
} finally {
|
||||
lockFlag.remove();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.central.common.redis.properties;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2019/1/6
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@ConfigurationProperties(prefix = "zlt.cache-manager")
|
||||
public class CacheManagerProperties {
|
||||
private List<CacheConfig> configs;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
public static class CacheConfig {
|
||||
/**
|
||||
* cache key
|
||||
*/
|
||||
private String key;
|
||||
/**
|
||||
* 过期时间,sec
|
||||
*/
|
||||
private long second = 60;
|
||||
}
|
||||
}
|
||||
+504
@@ -0,0 +1,504 @@
|
||||
package com.central.common.redis.template;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.springframework.data.redis.connection.RedisClusterNode;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.connection.RedisServerCommands;
|
||||
import org.springframework.data.redis.core.HashOperations;
|
||||
import org.springframework.data.redis.core.ListOperations;
|
||||
import org.springframework.data.redis.core.RedisCallback;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.RedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Redis Repository
|
||||
* redis 基本操作 可扩展,基本够用了
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
@Slf4j
|
||||
public class RedisRepository {
|
||||
/**
|
||||
* 默认编码
|
||||
*/
|
||||
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
|
||||
|
||||
/**
|
||||
* key序列化
|
||||
*/
|
||||
private static final StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();
|
||||
|
||||
/**
|
||||
* value 序列化
|
||||
*/
|
||||
private static final JdkSerializationRedisSerializer OBJECT_SERIALIZER = new JdkSerializationRedisSerializer();
|
||||
|
||||
/**
|
||||
* Spring Redis Template
|
||||
*/
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
public RedisRepository(RedisTemplate<String, Object> redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.redisTemplate.setKeySerializer(STRING_SERIALIZER);
|
||||
this.redisTemplate.setValueSerializer(OBJECT_SERIALIZER);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取链接工厂
|
||||
*/
|
||||
public RedisConnectionFactory getConnectionFactory() {
|
||||
return this.redisTemplate.getConnectionFactory();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 RedisTemplate对象
|
||||
*/
|
||||
public RedisTemplate<String, Object> getRedisTemplate() {
|
||||
return redisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空DB
|
||||
*
|
||||
* @param node redis 节点
|
||||
*/
|
||||
public void flushDB(RedisClusterNode node) {
|
||||
this.redisTemplate.opsForCluster().flushDb(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加到带有 过期时间的 缓存
|
||||
*
|
||||
* @param key redis主键
|
||||
* @param value 值
|
||||
* @param time 过期时间(单位秒)
|
||||
*/
|
||||
public void setExpire(final byte[] key, final byte[] value, final long time) {
|
||||
redisTemplate.execute((RedisCallback<Long>) connection -> {
|
||||
connection.setEx(key, time, value);
|
||||
log.debug("[redisTemplate redis]放入 缓存 url:{} ========缓存时间为{}秒", key, time);
|
||||
return 1L;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加到带有 过期时间的 缓存
|
||||
*
|
||||
* @param key redis主键
|
||||
* @param value 值
|
||||
* @param time 过期时间(单位秒)
|
||||
*/
|
||||
public void setExpire(final String key, final Object value, final long time) {
|
||||
redisTemplate.execute((RedisCallback<Long>) connection -> {
|
||||
RedisSerializer<String> serializer = getRedisSerializer();
|
||||
byte[] keys = serializer.serialize(key);
|
||||
byte[] values = OBJECT_SERIALIZER.serialize(value);
|
||||
connection.setEx(keys, time, values);
|
||||
return 1L;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销
|
||||
*
|
||||
* @param keys redis主键数组
|
||||
* @param values 值数组
|
||||
* @param time 过期时间(单位秒)
|
||||
*/
|
||||
public void setExpire(final String[] keys, final Object[] values, final long time) {
|
||||
redisTemplate.execute((RedisCallback<Long>) connection -> {
|
||||
RedisSerializer<String> serializer = getRedisSerializer();
|
||||
for (int i = 0; i < keys.length; i++) {
|
||||
byte[] bKeys = serializer.serialize(keys[i]);
|
||||
byte[] bValues = OBJECT_SERIALIZER.serialize(values[i]);
|
||||
connection.setEx(bKeys, time, bValues);
|
||||
}
|
||||
return 1L;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销
|
||||
*
|
||||
* @param keys the keys
|
||||
* @param values the values
|
||||
*/
|
||||
public void set(final String[] keys, final Object[] values) {
|
||||
redisTemplate.execute((RedisCallback<Long>) connection -> {
|
||||
RedisSerializer<String> serializer = getRedisSerializer();
|
||||
for (int i = 0; i < keys.length; i++) {
|
||||
byte[] bKeys = serializer.serialize(keys[i]);
|
||||
byte[] bValues = OBJECT_SERIALIZER.serialize(values[i]);
|
||||
connection.set(bKeys, bValues);
|
||||
}
|
||||
return 1L;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 添加到缓存
|
||||
*
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
*/
|
||||
public void set(final String key, final Object value) {
|
||||
redisTemplate.execute((RedisCallback<Long>) connection -> {
|
||||
RedisSerializer<String> serializer = getRedisSerializer();
|
||||
byte[] keys = serializer.serialize(key);
|
||||
byte[] values = OBJECT_SERIALIZER.serialize(value);
|
||||
connection.set(keys, values);
|
||||
log.debug("[redisTemplate redis]放入 缓存 url:{}", key);
|
||||
return 1L;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询在这个时间段内即将过期的key
|
||||
*
|
||||
* @param key the key
|
||||
* @param time the time
|
||||
* @return the list
|
||||
*/
|
||||
public List<String> willExpire(final String key, final long time) {
|
||||
final List<String> keysList = new ArrayList<>();
|
||||
redisTemplate.execute((RedisCallback<List<String>>) connection -> {
|
||||
Set<String> keys = redisTemplate.keys(key + "*");
|
||||
for (String key1 : keys) {
|
||||
Long ttl = connection.ttl(key1.getBytes(DEFAULT_CHARSET));
|
||||
if (0 <= ttl && ttl <= 2 * time) {
|
||||
keysList.add(key1);
|
||||
}
|
||||
}
|
||||
return keysList;
|
||||
});
|
||||
return keysList;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 查询在以keyPatten的所有 key
|
||||
*
|
||||
* @param keyPatten the key patten
|
||||
* @return the set
|
||||
*/
|
||||
public Set<String> keys(final String keyPatten) {
|
||||
return redisTemplate.execute((RedisCallback<Set<String>>) connection -> redisTemplate.keys(keyPatten + "*"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据key获取对象
|
||||
*
|
||||
* @param key the key
|
||||
* @return the byte [ ]
|
||||
*/
|
||||
public byte[] get(final byte[] key) {
|
||||
byte[] result = redisTemplate.execute((RedisCallback<byte[]>) connection -> connection.get(key));
|
||||
log.debug("[redisTemplate redis]取出 缓存 url:{} ", key);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据key获取对象
|
||||
*
|
||||
* @param key the key
|
||||
* @return the string
|
||||
*/
|
||||
public Object get(final String key) {
|
||||
Object resultStr = redisTemplate.execute((RedisCallback<Object>) connection -> {
|
||||
RedisSerializer<String> serializer = getRedisSerializer();
|
||||
byte[] keys = serializer.serialize(key);
|
||||
byte[] values = connection.get(keys);
|
||||
return OBJECT_SERIALIZER.deserialize(values);
|
||||
});
|
||||
log.debug("[redisTemplate redis]取出 缓存 url:{} ", key);
|
||||
return resultStr;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 根据key获取对象
|
||||
*
|
||||
* @param keyPatten the key patten
|
||||
* @return the keys values
|
||||
*/
|
||||
public Map<String, Object> getKeysValues(final String keyPatten) {
|
||||
log.debug("[redisTemplate redis] getValues() patten={} ", keyPatten);
|
||||
return redisTemplate.execute((RedisCallback<Map<String, Object>>) connection -> {
|
||||
RedisSerializer<String> serializer = getRedisSerializer();
|
||||
Map<String, Object> maps = new HashMap<>(16);
|
||||
Set<String> keys = redisTemplate.keys(keyPatten + "*");
|
||||
if (CollectionUtils.isNotEmpty(keys)) {
|
||||
for (String key : keys) {
|
||||
byte[] bKeys = serializer.serialize(key);
|
||||
byte[] bValues = connection.get(bKeys);
|
||||
Object value = OBJECT_SERIALIZER.deserialize(bValues);
|
||||
maps.put(key, value);
|
||||
}
|
||||
}
|
||||
return maps;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ops for hash hash operations.
|
||||
*
|
||||
* @return the hash operations
|
||||
*/
|
||||
public HashOperations<String, String, Object> opsForHash() {
|
||||
return redisTemplate.opsForHash();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对HashMap操作
|
||||
*
|
||||
* @param key the key
|
||||
* @param hashKey the hash key
|
||||
* @param hashValue the hash value
|
||||
*/
|
||||
public void putHashValue(String key, String hashKey, Object hashValue) {
|
||||
log.debug("[redisTemplate redis] putHashValue() key={},hashKey={},hashValue={} ", key, hashKey, hashValue);
|
||||
opsForHash().put(key, hashKey, hashValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单个field对应的值
|
||||
*
|
||||
* @param key the key
|
||||
* @param hashKey the hash key
|
||||
* @return the hash values
|
||||
*/
|
||||
public Object getHashValues(String key, String hashKey) {
|
||||
log.debug("[redisTemplate redis] getHashValues() key={},hashKey={}", key, hashKey);
|
||||
return opsForHash().get(key, hashKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据key值删除
|
||||
*
|
||||
* @param key the key
|
||||
* @param hashKeys the hash keys
|
||||
*/
|
||||
public void delHashValues(String key, Object... hashKeys) {
|
||||
log.debug("[redisTemplate redis] delHashValues() key={}", key);
|
||||
opsForHash().delete(key, hashKeys);
|
||||
}
|
||||
|
||||
/**
|
||||
* key只匹配map
|
||||
*
|
||||
* @param key the key
|
||||
* @return the hash value
|
||||
*/
|
||||
public Map<String, Object> getHashValue(String key) {
|
||||
log.debug("[redisTemplate redis] getHashValue() key={}", key);
|
||||
return opsForHash().entries(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量添加
|
||||
*
|
||||
* @param key the key
|
||||
* @param map the map
|
||||
*/
|
||||
public void putHashValues(String key, Map<String, Object> map) {
|
||||
opsForHash().putAll(key, map);
|
||||
}
|
||||
|
||||
/**
|
||||
* 集合数量
|
||||
*
|
||||
* @return the long
|
||||
*/
|
||||
public long dbSize() {
|
||||
return redisTemplate.execute(RedisServerCommands::dbSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空redis存储的数据
|
||||
*
|
||||
* @return the string
|
||||
*/
|
||||
public String flushDB() {
|
||||
return redisTemplate.execute((RedisCallback<String>) connection -> {
|
||||
connection.flushDb();
|
||||
return "ok";
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断某个主键是否存在
|
||||
*
|
||||
* @param key the key
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean exists(final String key) {
|
||||
return redisTemplate.execute((RedisCallback<Boolean>) connection -> connection.exists(key.getBytes(DEFAULT_CHARSET)));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 删除key
|
||||
*
|
||||
* @param keys the keys
|
||||
* @return the long
|
||||
*/
|
||||
public long del(final String... keys) {
|
||||
return redisTemplate.execute((RedisCallback<Long>) connection -> {
|
||||
long result = 0;
|
||||
for (String key : keys) {
|
||||
result = connection.del(key.getBytes(DEFAULT_CHARSET));
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 RedisSerializer
|
||||
*
|
||||
* @return the redis serializer
|
||||
*/
|
||||
protected RedisSerializer<String> getRedisSerializer() {
|
||||
return redisTemplate.getStringSerializer();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对某个主键对应的值加一,value值必须是全数字的字符串
|
||||
*
|
||||
* @param key the key
|
||||
* @return the long
|
||||
*/
|
||||
public long incr(final String key) {
|
||||
return redisTemplate.execute((RedisCallback<Long>) connection -> {
|
||||
RedisSerializer<String> redisSerializer = getRedisSerializer();
|
||||
return connection.incr(redisSerializer.serialize(key));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* redis List 引擎
|
||||
*
|
||||
* @return the list operations
|
||||
*/
|
||||
public ListOperations<String, Object> opsForList() {
|
||||
return redisTemplate.opsForList();
|
||||
}
|
||||
|
||||
/**
|
||||
* redis List数据结构 : 将一个或多个值 value 插入到列表 key 的表头
|
||||
*
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
* @return the long
|
||||
*/
|
||||
public Long leftPush(String key, Object value) {
|
||||
return opsForList().leftPush(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* redis List数据结构 : 移除并返回列表 key 的头元素
|
||||
*
|
||||
* @param key the key
|
||||
* @return the string
|
||||
*/
|
||||
public Object leftPop(String key) {
|
||||
return opsForList().leftPop(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* redis List数据结构 :将一个或多个值 value 插入到列表 key 的表尾(最右边)。
|
||||
*
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
* @return the long
|
||||
*/
|
||||
public Long in(String key, Object value) {
|
||||
return opsForList().rightPush(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* redis List数据结构 : 移除并返回列表 key 的末尾元素
|
||||
*
|
||||
* @param key the key
|
||||
* @return the string
|
||||
*/
|
||||
public Object rightPop(String key) {
|
||||
return opsForList().rightPop(key);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* redis List数据结构 : 返回列表 key 的长度 ; 如果 key 不存在,则 key 被解释为一个空列表,返回 0 ; 如果 key 不是列表类型,返回一个错误。
|
||||
*
|
||||
* @param key the key
|
||||
* @return the long
|
||||
*/
|
||||
public Long length(String key) {
|
||||
return opsForList().size(key);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* redis List数据结构 : 根据参数 i 的值,移除列表中与参数 value 相等的元素
|
||||
*
|
||||
* @param key the key
|
||||
* @param i the
|
||||
* @param value the value
|
||||
*/
|
||||
public void remove(String key, long i, Object value) {
|
||||
opsForList().remove(key, i, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* redis List数据结构 : 将列表 key 下标为 index 的元素的值设置为 value
|
||||
*
|
||||
* @param key the key
|
||||
* @param index the index
|
||||
* @param value the value
|
||||
*/
|
||||
public void set(String key, long index, Object value) {
|
||||
opsForList().set(key, index, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* redis List数据结构 : 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 end 指定。
|
||||
*
|
||||
* @param key the key
|
||||
* @param start the start
|
||||
* @param end the end
|
||||
* @return the list
|
||||
*/
|
||||
public List<Object> getList(String key, int start, int end) {
|
||||
return opsForList().range(key, start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* redis List数据结构 : 批量存储
|
||||
*
|
||||
* @param key the key
|
||||
* @param list the list
|
||||
* @return the long
|
||||
*/
|
||||
public Long leftPushAll(String key, List<String> list) {
|
||||
return opsForList().leftPushAll(key, list);
|
||||
}
|
||||
|
||||
/**
|
||||
* redis List数据结构 : 将值 value 插入到列表 key 当中,位于值 index 之前或之后,默认之后。
|
||||
*
|
||||
* @param key the key
|
||||
* @param index the index
|
||||
* @param value the value
|
||||
*/
|
||||
public void insert(String key, long index, Object value) {
|
||||
opsForList().set(key, index, value);
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.central.common.redis.util;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.core.serializer.support.DeserializingConverter;
|
||||
import org.springframework.core.serializer.support.SerializingConverter;
|
||||
import org.springframework.data.redis.serializer.RedisSerializer;
|
||||
import org.springframework.data.redis.serializer.SerializationException;
|
||||
|
||||
/**
|
||||
* 此时定义的序列化操作表示可以序列化所有类的对象,当然,这个对象所在的类一定要实现序列化接口
|
||||
*
|
||||
* @author zlt
|
||||
*/
|
||||
public class RedisObjectSerializer implements RedisSerializer<Object> {
|
||||
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; // 做一个空数组,不是null
|
||||
// 为了方便进行对象与字节数组的转换,所以应该首先准备出两个转换器
|
||||
private Converter<Object, byte[]> serializingConverter = new SerializingConverter();
|
||||
private Converter<byte[], Object> deserializingConverter = new DeserializingConverter();
|
||||
|
||||
@Override
|
||||
public byte[] serialize(Object obj) throws SerializationException {
|
||||
if (obj == null) { // 这个时候没有要序列化的对象出现,所以返回的字节数组应该就是一个空数组
|
||||
return EMPTY_BYTE_ARRAY;
|
||||
}
|
||||
return this.serializingConverter.convert(obj); // 将对象变为字节数组
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object deserialize(byte[] data) throws SerializationException {
|
||||
if (data == null || data.length == 0) { // 此时没有对象的内容信息
|
||||
return null;
|
||||
}
|
||||
return this.deserializingConverter.convert(data);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
com.central.common.redis.RedisAutoConfigure
|
||||
@@ -0,0 +1,19 @@
|
||||
--lua 下标从 1 开始
|
||||
-- 限流 key
|
||||
local key = KEYS[1]
|
||||
-- 限流大小
|
||||
local limit = tonumber(ARGV[1])
|
||||
|
||||
-- 获取当前流量大小
|
||||
local curentLimit = tonumber(redis.call('get', key) or "0")
|
||||
|
||||
if curentLimit + 1 > limit then
|
||||
-- 达到限流大小 返回
|
||||
return 0;
|
||||
else
|
||||
-- 没有达到阈值 value + 1
|
||||
redis.call("INCRBY", key, 1)
|
||||
redis.call("EXPIRE", key, 2)
|
||||
return curentLimit + 1
|
||||
end
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
/target/
|
||||
*.iml
|
||||
@@ -0,0 +1,53 @@
|
||||
<?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">
|
||||
<parent>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-commons</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<packaging>jar</packaging>
|
||||
<artifactId>zlt-ribbon-spring-boot-starter</artifactId>
|
||||
<description>远程通信通用组件</description>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-common-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>HdrHistogram</artifactId>
|
||||
<groupId>org.hdrhistogram</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>HdrHistogram</artifactId>
|
||||
<groupId>org.hdrhistogram</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.central.common.ribbon;
|
||||
|
||||
import feign.Logger;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Feign统一配置
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/9/18 14:04
|
||||
*/
|
||||
@Configuration
|
||||
public class FeignAutoConfigure {
|
||||
|
||||
/**
|
||||
* Feign 日志级别
|
||||
*/
|
||||
@Bean
|
||||
Logger.Level feignLoggerLevel() {
|
||||
return Logger.Level.FULL;
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.central.common.ribbon;
|
||||
|
||||
import com.central.common.ribbon.config.RestTemplateProperties;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.config.Registry;
|
||||
import org.apache.http.config.RegistryBuilder;
|
||||
import org.apache.http.conn.socket.ConnectionSocketFactory;
|
||||
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018/11/17
|
||||
*/
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(RestTemplateProperties.class)
|
||||
public class RestTemplateAutoConfigure {
|
||||
@Autowired
|
||||
private RestTemplateProperties restTemplateProperties;
|
||||
|
||||
@LoadBalanced
|
||||
@Bean
|
||||
public RestTemplate restTemplate() {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
restTemplate.setRequestFactory(httpRequestFactory());
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* httpclient 实现的ClientHttpRequestFactory
|
||||
*/
|
||||
@Bean
|
||||
public ClientHttpRequestFactory httpRequestFactory() {
|
||||
return new HttpComponentsClientHttpRequestFactory(httpClient());
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用连接池的 httpclient
|
||||
*/
|
||||
@Bean
|
||||
public HttpClient httpClient() {
|
||||
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("http", PlainConnectionSocketFactory.getSocketFactory())
|
||||
.register("https", SSLConnectionSocketFactory.getSocketFactory())
|
||||
.build();
|
||||
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
|
||||
// 最大链接数
|
||||
connectionManager.setMaxTotal(restTemplateProperties.getMaxTotal());
|
||||
// 同路由并发数20
|
||||
connectionManager.setDefaultMaxPerRoute(restTemplateProperties.getMaxPerRoute());
|
||||
|
||||
RequestConfig requestConfig = RequestConfig.custom()
|
||||
// 读超时
|
||||
.setSocketTimeout(restTemplateProperties.getReadTimeout())
|
||||
// 链接超时
|
||||
.setConnectTimeout(restTemplateProperties.getConnectTimeout())
|
||||
// 链接不够用的等待时间
|
||||
.setConnectionRequestTimeout(restTemplateProperties.getReadTimeout())
|
||||
.build();
|
||||
|
||||
return HttpClientBuilder.create()
|
||||
.setDefaultRequestConfig(requestConfig)
|
||||
.setConnectionManager(connectionManager)
|
||||
.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.central.common.ribbon;
|
||||
|
||||
import com.central.common.ribbon.config.RestTemplateProperties;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
|
||||
import org.springframework.cloud.netflix.ribbon.DefaultPropertiesFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Ribbon扩展配置类
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/11/17 9:24
|
||||
*/
|
||||
@Configuration
|
||||
@EnableCircuitBreaker
|
||||
@EnableConfigurationProperties(RestTemplateProperties.class)
|
||||
public class RibbonAutoConfigure {
|
||||
|
||||
@Bean
|
||||
public DefaultPropertiesFactory defaultPropertiesFactory() {
|
||||
return new DefaultPropertiesFactory();
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.central.common.ribbon.config;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* RestTemplate 配置
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2017/11/17
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@ConfigurationProperties(prefix = "zlt.rest-template")
|
||||
public class RestTemplateProperties {
|
||||
/**
|
||||
* 最大链接数
|
||||
*/
|
||||
private int maxTotal = 200;
|
||||
/**
|
||||
* 同路由最大并发数
|
||||
*/
|
||||
private int maxPerRoute = 50;
|
||||
/**
|
||||
* 读取超时时间 ms
|
||||
*/
|
||||
private int readTimeout = 35000;
|
||||
/**
|
||||
* 链接超时时间 ms
|
||||
*/
|
||||
private int connectTimeout = 10000;
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package org.springframework.cloud.netflix.ribbon;
|
||||
|
||||
import com.netflix.loadbalancer.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.springframework.cloud.netflix.ribbon.SpringClientFactory.NAMESPACE;
|
||||
|
||||
/**
|
||||
* 扩展 spring cloud ribbon的PropertiesFactory
|
||||
* 使其能够支持 配置全局的ribbon.NFLoadBalancerRuleClassName=package.YourRule
|
||||
* 然后各个微服务还可以根据自身情况做个性化定制。如:SERVICE_ID.ribbon.NFLoadBalancerRuleClassName=package.YourRule
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/11/17 9:29
|
||||
*/
|
||||
public class DefaultPropertiesFactory extends PropertiesFactory {
|
||||
|
||||
@Autowired
|
||||
private Environment environment;
|
||||
|
||||
private Map<Class, String> classToProperty = new HashMap<>(5);
|
||||
|
||||
public DefaultPropertiesFactory() {
|
||||
super();
|
||||
classToProperty.put(ILoadBalancer.class, "NFLoadBalancerClassName");
|
||||
classToProperty.put(IPing.class, "NFLoadBalancerPingClassName");
|
||||
classToProperty.put(IRule.class, "NFLoadBalancerRuleClassName");
|
||||
classToProperty.put(ServerList.class, "NIWSServerListClassName");
|
||||
classToProperty.put(ServerListFilter.class, "NIWSServerListFilterClassName");
|
||||
}
|
||||
|
||||
/**
|
||||
* 重写 支持 ribbon.NFLoadBalancerRuleClassName=package.YourRule 全局配置的方式
|
||||
*/
|
||||
@Override
|
||||
public String getClassName(Class clazz, String name) {
|
||||
String className = super.getClassName(clazz, name);
|
||||
// 读取全局配置
|
||||
if(!StringUtils.hasText(className) && this.classToProperty.containsKey(clazz)){
|
||||
String classNameProperty = this.classToProperty.get(clazz);
|
||||
className = environment.getProperty(NAMESPACE + "." + classNameProperty);
|
||||
}
|
||||
return className;
|
||||
}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
com.central.common.ribbon.RibbonAutoConfigure,\
|
||||
com.central.common.ribbon.FeignAutoConfigure,\
|
||||
com.central.common.ribbon.RestTemplateAutoConfigure
|
||||
@@ -0,0 +1,2 @@
|
||||
/target/
|
||||
*.iml
|
||||
@@ -0,0 +1,136 @@
|
||||
# 简介
|
||||
该项目主要利用Spring Boot的自动化配置特性来实现快速的将swagger2引入spring boot应用来生成API文档,简化原生使用swagger2的整合代码。
|
||||
|
||||
# 如何使用
|
||||
dependency引入即可。默认情况下就能产生所有当前Spring MVC加载的请求映射文档。
|
||||
|
||||
## 配置示例
|
||||
```properties
|
||||
swagger.enabled=true
|
||||
|
||||
swagger.title=spring-boot-starter-swagger
|
||||
swagger.description=Starter for swagger 2.x
|
||||
swagger.version=1.4.0.RELEASE
|
||||
swagger.license=Apache License, Version 2.0
|
||||
swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html
|
||||
swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger
|
||||
swagger.contact.name=didi
|
||||
swagger.contact.url=http://blog.didispace.com
|
||||
swagger.contact.email=dyc87112@qq.com
|
||||
swagger.base-package=com.didispace
|
||||
swagger.base-path=/**
|
||||
swagger.exclude-path=/error, /ops/**
|
||||
|
||||
swagger.globalOperationParameters[0].name=name one
|
||||
swagger.globalOperationParameters[0].description=some description one
|
||||
swagger.globalOperationParameters[0].modelRef=string
|
||||
swagger.globalOperationParameters[0].parameterType=header
|
||||
swagger.globalOperationParameters[0].required=true
|
||||
swagger.globalOperationParameters[1].name=name two
|
||||
swagger.globalOperationParameters[1].description=some description two
|
||||
swagger.globalOperationParameters[1].modelRef=string
|
||||
swagger.globalOperationParameters[1].parameterType=body
|
||||
swagger.globalOperationParameters[1].required=false
|
||||
```
|
||||
|
||||
## 配置说明
|
||||
|
||||
### 默认配置
|
||||
|
||||
```
|
||||
- swagger.enabled=是否启用swagger,默认:true
|
||||
- swagger.title=标题
|
||||
- swagger.description=描述
|
||||
- swagger.version=版本
|
||||
- swagger.license=许可证
|
||||
- swagger.licenseUrl=许可证URL
|
||||
- swagger.termsOfServiceUrl=服务条款URL
|
||||
- swagger.contact.name=维护人
|
||||
- swagger.contact.url=维护人URL
|
||||
- swagger.contact.email=维护人email
|
||||
- swagger.base-package=swagger扫描的基础包,默认:全扫描
|
||||
- swagger.base-path=需要处理的基础URL规则,默认:/**
|
||||
- swagger.exclude-path=需要排除的URL规则,默认:空
|
||||
- swagger.host=文档的host信息,默认:空
|
||||
- globalOperationParameters用于设置全局的参数,比如:header部分的accessToken等。该参数支持指定docket的配置。
|
||||
- swagger.globalOperationParameters[0].name=参数名
|
||||
- swagger.globalOperationParameters[0].description=描述信息
|
||||
- swagger.globalOperationParameters[0].modelRef=指定参数类型
|
||||
- swagger.globalOperationParameters[0].parameterType=指定参数存放位置,可选header,query,path,body.form
|
||||
- swagger.globalOperationParameters[0].required=指定参数是否必传,true,false
|
||||
```
|
||||
|
||||
### Path规则说明
|
||||
|
||||
`swagger.base-path`和`swagger.exclude-path`使用ANT规则配置。
|
||||
|
||||
我们可以使用`swagger.base-path`来指定所有需要生成文档的请求路径基础规则,然后再利用`swagger.exclude-path`来剔除部分我们不需要的。
|
||||
|
||||
比如,通常我们可以这样设置:
|
||||
|
||||
```properties
|
||||
management.context-path=/ops
|
||||
|
||||
swagger.base-path=/**
|
||||
swagger.exclude-path=/ops/**, /error
|
||||
```
|
||||
|
||||
上面的设置将解析所有除了`/ops/`开始以及spring boot自带`/error`请求路径。
|
||||
|
||||
其中,`exclude-path`可以配合`management.context-path=/ops`设置的spring boot actuator的context-path来排除所有监控端点。
|
||||
|
||||
### 分组配置
|
||||
|
||||
当我们一个项目的API非常多的时候,我们希望对API文档实现分组。从1.2.0.RELEASE开始,将支持分组配置功能。
|
||||
|
||||

|
||||
|
||||
具体配置内容如下:
|
||||
|
||||
```
|
||||
- swagger.docket.<name>.title=标题
|
||||
- swagger.docket.<name>.description=描述
|
||||
- swagger.docket.<name>.version=版本
|
||||
- swagger.docket.<name>.license=许可证
|
||||
- swagger.docket.<name>.licenseUrl=许可证URL
|
||||
- swagger.docket.<name>.termsOfServiceUrl=服务条款URL
|
||||
- swagger.docket.<name>.contact.name=维护人
|
||||
- swagger.docket.<name>.contact.url=维护人URL
|
||||
- swagger.docket.<name>.contact.email=维护人email
|
||||
- swagger.docket.<name>.base-package=swagger扫描的基础包,默认:全扫描
|
||||
- swagger.docket.<name>.base-path=需要处理的基础URL规则,默认:/**
|
||||
- swagger.docket.<name>.exclude-path=需要排除的URL规则,默认:空
|
||||
- swagger.docket.<name>.name=参数名
|
||||
- swagger.docket.<name>.modelRef=指定参数类型
|
||||
- swagger.docket.<name>.parameterType=指定参数存放位置,可选header,query,path,body.form
|
||||
- swagger.docket.<name>.required=true=指定参数是否必传,true,false
|
||||
- swagger.docket.<name>.globalOperationParameters[0].name=参数名
|
||||
- swagger.docket.<name>.globalOperationParameters[0].description=描述信息
|
||||
- swagger.docket.<name>.globalOperationParameters[0].modelRef=指定参数存放位置,可选header,query,path,body.form
|
||||
- swagger.docket.<name>.globalOperationParameters[0].parameterType=指定参数是否必传,true,false
|
||||
```
|
||||
|
||||
说明:`<name>`为swagger文档的分组名称,同一个项目中可以配置多个分组,用来划分不同的API文档。
|
||||
|
||||
|
||||
**分组配置示例**
|
||||
|
||||
```properties
|
||||
swagger.docket.aaa.title=group-a
|
||||
swagger.docket.aaa.description=Starter for swagger 2.x
|
||||
swagger.docket.aaa.version=1.3.0.RELEASE
|
||||
swagger.docket.aaa.termsOfServiceUrl=https://gitee.com/didispace/spring-boot-starter-swagger
|
||||
swagger.docket.aaa.contact.name=zhaiyongchao
|
||||
swagger.docket.aaa.contact.url=http://spring4all.com/
|
||||
swagger.docket.aaa.contact.email=didi@potatomato.club
|
||||
swagger.docket.aaa.excludePath=/ops/**
|
||||
swagger.docket.aaa.globalOperationParameters[0].name=name three
|
||||
swagger.docket.aaa.globalOperationParameters[0].description=some description three override
|
||||
swagger.docket.aaa.globalOperationParameters[0].modelRef=string
|
||||
swagger.docket.aaa.globalOperationParameters[0].parameterType=header
|
||||
|
||||
swagger.docket.bbb.title=group-bbb
|
||||
swagger.docket.bbb.basePackage=com.yonghui
|
||||
```
|
||||
|
||||
说明:默认配置与分组配置可以一起使用。在分组配置中没有配置的内容将使用默认配置替代,所以默认配置可以作为分组配置公共部分属性的配置。`swagger.docket.aaa.globalOperationParameters[0].name`会覆盖同名的全局配置。
|
||||
@@ -0,0 +1,28 @@
|
||||
<?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">
|
||||
<parent>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-commons</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<packaging>jar</packaging>
|
||||
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
|
||||
<description>swagger通用组件</description>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.central.common.swagger2;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/11/18 9:20
|
||||
*/
|
||||
@Configuration
|
||||
@ConditionalOnProperty(name = "zlt.swagger.enabled", matchIfMissing = true)
|
||||
@Import({
|
||||
Swagger2DocumentationConfiguration.class
|
||||
})
|
||||
public class Swagger2Configuration {
|
||||
}
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
package com.central.common.swagger2;
|
||||
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.base.Predicates;
|
||||
import com.google.common.collect.Lists;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.BeanFactoryAware;
|
||||
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import springfox.documentation.builders.ApiInfoBuilder;
|
||||
import springfox.documentation.builders.ParameterBuilder;
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
import springfox.documentation.schema.ModelRef;
|
||||
import springfox.documentation.service.ApiInfo;
|
||||
import springfox.documentation.service.ApiKey;
|
||||
import springfox.documentation.service.AuthorizationScope;
|
||||
import springfox.documentation.service.Contact;
|
||||
import springfox.documentation.service.Parameter;
|
||||
import springfox.documentation.service.SecurityReference;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spi.service.contexts.SecurityContext;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date 2018/11/18 9:22
|
||||
*/
|
||||
@Configuration
|
||||
@Import( {
|
||||
Swagger2Configuration.class
|
||||
})
|
||||
public class SwaggerAutoConfiguration implements BeanFactoryAware {
|
||||
|
||||
private BeanFactory beanFactory;
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public SwaggerProperties swaggerProperties() {
|
||||
return new SwaggerProperties();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnProperty(name = "zlt.swagger.enabled", matchIfMissing = true)
|
||||
public List<Docket> createRestApi(SwaggerProperties swaggerProperties) {
|
||||
ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
|
||||
List<Docket> docketList = new LinkedList<>();
|
||||
|
||||
// 没有分组
|
||||
if (swaggerProperties.getDocket().size() == 0) {
|
||||
final Docket docket = createDocket(swaggerProperties);
|
||||
configurableBeanFactory.registerSingleton("defaultDocket", docket);
|
||||
docketList.add(docket);
|
||||
return docketList;
|
||||
}
|
||||
|
||||
// 分组创建
|
||||
for (String groupName : swaggerProperties.getDocket().keySet()) {
|
||||
SwaggerProperties.DocketInfo docketInfo = swaggerProperties.getDocket().get(groupName);
|
||||
|
||||
ApiInfo apiInfo = new ApiInfoBuilder()
|
||||
.title(docketInfo.getTitle().isEmpty() ? swaggerProperties.getTitle() : docketInfo.getTitle())
|
||||
.description(docketInfo.getDescription().isEmpty() ? swaggerProperties.getDescription() : docketInfo.getDescription())
|
||||
.version(docketInfo.getVersion().isEmpty() ? swaggerProperties.getVersion() : docketInfo.getVersion())
|
||||
.license(docketInfo.getLicense().isEmpty() ? swaggerProperties.getLicense() : docketInfo.getLicense())
|
||||
.licenseUrl(docketInfo.getLicenseUrl().isEmpty() ? swaggerProperties.getLicenseUrl() : docketInfo.getLicenseUrl())
|
||||
.contact(
|
||||
new Contact(
|
||||
docketInfo.getContact().getName().isEmpty() ? swaggerProperties.getContact().getName() : docketInfo.getContact().getName(),
|
||||
docketInfo.getContact().getUrl().isEmpty() ? swaggerProperties.getContact().getUrl() : docketInfo.getContact().getUrl(),
|
||||
docketInfo.getContact().getEmail().isEmpty() ? swaggerProperties.getContact().getEmail() : docketInfo.getContact().getEmail()
|
||||
)
|
||||
)
|
||||
.termsOfServiceUrl(docketInfo.getTermsOfServiceUrl().isEmpty() ? swaggerProperties.getTermsOfServiceUrl() : docketInfo.getTermsOfServiceUrl())
|
||||
.build();
|
||||
|
||||
// base-path处理
|
||||
// 当没有配置任何path的时候,解析/**
|
||||
if (docketInfo.getBasePath().isEmpty()) {
|
||||
docketInfo.getBasePath().add("/**");
|
||||
}
|
||||
List<Predicate<String>> basePath = new ArrayList<>(docketInfo.getBasePath().size());
|
||||
for (String path : docketInfo.getBasePath()) {
|
||||
basePath.add(PathSelectors.ant(path));
|
||||
}
|
||||
|
||||
// exclude-path处理
|
||||
List<Predicate<String>> excludePath = new ArrayList<>(docketInfo.getExcludePath().size());
|
||||
for (String path : docketInfo.getExcludePath()) {
|
||||
excludePath.add(PathSelectors.ant(path));
|
||||
}
|
||||
|
||||
Docket docket = new Docket(DocumentationType.SWAGGER_2)
|
||||
.host(swaggerProperties.getHost())
|
||||
.apiInfo(apiInfo)
|
||||
.globalOperationParameters(assemblyGlobalOperationParameters(swaggerProperties.getGlobalOperationParameters(),
|
||||
docketInfo.getGlobalOperationParameters()))
|
||||
.groupName(groupName)
|
||||
.select()
|
||||
.apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage()))
|
||||
.paths(
|
||||
Predicates.and(
|
||||
Predicates.not(Predicates.or(excludePath)),
|
||||
Predicates.or(basePath)
|
||||
)
|
||||
)
|
||||
.build()
|
||||
.securitySchemes(securitySchemes())
|
||||
.securityContexts(securityContexts());
|
||||
|
||||
configurableBeanFactory.registerSingleton(groupName, docket);
|
||||
docketList.add(docket);
|
||||
}
|
||||
return docketList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 Docket对象
|
||||
*
|
||||
* @param swaggerProperties swagger配置
|
||||
* @return Docket
|
||||
*/
|
||||
private Docket createDocket(final SwaggerProperties swaggerProperties) {
|
||||
ApiInfo apiInfo = new ApiInfoBuilder()
|
||||
.title(swaggerProperties.getTitle())
|
||||
.description(swaggerProperties.getDescription())
|
||||
.version(swaggerProperties.getVersion())
|
||||
.license(swaggerProperties.getLicense())
|
||||
.licenseUrl(swaggerProperties.getLicenseUrl())
|
||||
.contact(new Contact(swaggerProperties.getContact().getName(),
|
||||
swaggerProperties.getContact().getUrl(),
|
||||
swaggerProperties.getContact().getEmail()))
|
||||
.termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
|
||||
.build();
|
||||
|
||||
// base-path处理
|
||||
// 当没有配置任何path的时候,解析/**
|
||||
if (swaggerProperties.getBasePath().isEmpty()) {
|
||||
swaggerProperties.getBasePath().add("/**");
|
||||
}
|
||||
List<Predicate<String>> basePath = new ArrayList<>();
|
||||
for (String path : swaggerProperties.getBasePath()) {
|
||||
basePath.add(PathSelectors.ant(path));
|
||||
}
|
||||
|
||||
// exclude-path处理
|
||||
List<Predicate<String>> excludePath = new ArrayList<>();
|
||||
for (String path : swaggerProperties.getExcludePath()) {
|
||||
excludePath.add(PathSelectors.ant(path));
|
||||
}
|
||||
|
||||
return new Docket(DocumentationType.SWAGGER_2)
|
||||
.host(swaggerProperties.getHost())
|
||||
.apiInfo(apiInfo)
|
||||
.globalOperationParameters(buildGlobalOperationParametersFromSwaggerProperties(
|
||||
swaggerProperties.getGlobalOperationParameters()))
|
||||
.select()
|
||||
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
|
||||
.paths(
|
||||
Predicates.and(
|
||||
Predicates.not(Predicates.or(excludePath)),
|
||||
Predicates.or(basePath)
|
||||
)
|
||||
)
|
||||
.build()
|
||||
.securitySchemes(securitySchemes())
|
||||
.securityContexts(securityContexts());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
|
||||
this.beanFactory = beanFactory;
|
||||
}
|
||||
|
||||
private List<SecurityContext> securityContexts() {
|
||||
List<SecurityContext> contexts = new ArrayList<>(1);
|
||||
SecurityContext securityContext = SecurityContext.builder()
|
||||
.securityReferences(defaultAuth())
|
||||
//.forPaths(PathSelectors.regex("^(?!auth).*$"))
|
||||
.build();
|
||||
contexts.add(securityContext);
|
||||
return contexts;
|
||||
}
|
||||
|
||||
private List<SecurityReference> defaultAuth() {
|
||||
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
|
||||
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
|
||||
authorizationScopes[0] = authorizationScope;
|
||||
List<SecurityReference> references = new ArrayList<>(1);
|
||||
references.add(new SecurityReference("Authorization", authorizationScopes));
|
||||
return references;
|
||||
}
|
||||
|
||||
private List<ApiKey> securitySchemes() {
|
||||
List<ApiKey> apiKeys = new ArrayList<>(1);
|
||||
ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
|
||||
apiKeys.add(apiKey);
|
||||
return apiKeys;
|
||||
}
|
||||
|
||||
private List<Parameter> buildGlobalOperationParametersFromSwaggerProperties(
|
||||
List<SwaggerProperties.GlobalOperationParameter> globalOperationParameters) {
|
||||
List<Parameter> parameters = Lists.newArrayList();
|
||||
|
||||
if (Objects.isNull(globalOperationParameters)) {
|
||||
return parameters;
|
||||
}
|
||||
for (SwaggerProperties.GlobalOperationParameter globalOperationParameter : globalOperationParameters) {
|
||||
parameters.add(new ParameterBuilder()
|
||||
.name(globalOperationParameter.getName())
|
||||
.description(globalOperationParameter.getDescription())
|
||||
.modelRef(new ModelRef(globalOperationParameter.getModelRef()))
|
||||
.parameterType(globalOperationParameter.getParameterType())
|
||||
.required(Boolean.parseBoolean(globalOperationParameter.getRequired()))
|
||||
.build());
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* 局部参数按照name覆盖局部参数
|
||||
*
|
||||
* @param globalOperationParameters
|
||||
* @param docketOperationParameters
|
||||
* @return
|
||||
*/
|
||||
private List<Parameter> assemblyGlobalOperationParameters(
|
||||
List<SwaggerProperties.GlobalOperationParameter> globalOperationParameters,
|
||||
List<SwaggerProperties.GlobalOperationParameter> docketOperationParameters) {
|
||||
|
||||
if (Objects.isNull(docketOperationParameters) || docketOperationParameters.isEmpty()) {
|
||||
return buildGlobalOperationParametersFromSwaggerProperties(globalOperationParameters);
|
||||
}
|
||||
|
||||
Set<String> docketNames = docketOperationParameters.stream()
|
||||
.map(SwaggerProperties.GlobalOperationParameter::getName)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
List<SwaggerProperties.GlobalOperationParameter> resultOperationParameters = Lists.newArrayList();
|
||||
|
||||
if (Objects.nonNull(globalOperationParameters)) {
|
||||
for (SwaggerProperties.GlobalOperationParameter parameter : globalOperationParameters) {
|
||||
if (!docketNames.contains(parameter.getName())) {
|
||||
resultOperationParameters.add(parameter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resultOperationParameters.addAll(docketOperationParameters);
|
||||
return buildGlobalOperationParametersFromSwaggerProperties(resultOperationParameters);
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package com.central.common.swagger2;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* swagger2 属性配置
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/11/18 9:17
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties("zlt.swagger")
|
||||
public class SwaggerProperties {
|
||||
/**是否开启swagger**/
|
||||
private Boolean enabled;
|
||||
/**标题**/
|
||||
private String title = "";
|
||||
/**描述**/
|
||||
private String description = "";
|
||||
/**版本**/
|
||||
private String version = "";
|
||||
/**许可证**/
|
||||
private String license = "";
|
||||
/**许可证URL**/
|
||||
private String licenseUrl = "";
|
||||
/**服务条款URL**/
|
||||
private String termsOfServiceUrl = "";
|
||||
|
||||
private Contact contact = new Contact();
|
||||
|
||||
/**swagger会解析的包路径**/
|
||||
private String basePackage = "";
|
||||
|
||||
/**swagger会解析的url规则**/
|
||||
private List<String> basePath = new ArrayList<>();
|
||||
/**在basePath基础上需要排除的url规则**/
|
||||
private List<String> excludePath = new ArrayList<>();
|
||||
|
||||
/**分组文档**/
|
||||
private Map<String, DocketInfo> docket = new LinkedHashMap<>();
|
||||
|
||||
/**host信息**/
|
||||
private String host = "";
|
||||
|
||||
/**全局参数配置**/
|
||||
private List<GlobalOperationParameter> globalOperationParameters;
|
||||
|
||||
|
||||
public static class GlobalOperationParameter{
|
||||
/**参数名**/
|
||||
private String name;
|
||||
|
||||
/**描述信息**/
|
||||
private String description;
|
||||
|
||||
/**指定参数类型**/
|
||||
private String modelRef;
|
||||
|
||||
/**参数放在哪个地方:header,query,path,body.form**/
|
||||
private String parameterType;
|
||||
|
||||
/**参数是否必须传**/
|
||||
private String required;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getModelRef() {
|
||||
return modelRef;
|
||||
}
|
||||
|
||||
public void setModelRef(String modelRef) {
|
||||
this.modelRef = modelRef;
|
||||
}
|
||||
|
||||
public String getParameterType() {
|
||||
return parameterType;
|
||||
}
|
||||
|
||||
public void setParameterType(String parameterType) {
|
||||
this.parameterType = parameterType;
|
||||
}
|
||||
|
||||
public String getRequired() {
|
||||
return required;
|
||||
}
|
||||
|
||||
public void setRequired(String required) {
|
||||
this.required = required;
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class DocketInfo {
|
||||
/**标题**/
|
||||
private String title = "";
|
||||
/**描述**/
|
||||
private String description = "";
|
||||
/**版本**/
|
||||
private String version = "";
|
||||
/**许可证**/
|
||||
private String license = "";
|
||||
/**许可证URL**/
|
||||
private String licenseUrl = "";
|
||||
/**服务条款URL**/
|
||||
private String termsOfServiceUrl = "";
|
||||
|
||||
private Contact contact = new Contact();
|
||||
|
||||
/**swagger会解析的包路径**/
|
||||
private String basePackage = "";
|
||||
|
||||
/**swagger会解析的url规则**/
|
||||
private List<String> basePath = new ArrayList<>();
|
||||
/**在basePath基础上需要排除的url规则**/
|
||||
private List<String> excludePath = new ArrayList<>();
|
||||
|
||||
private List<GlobalOperationParameter> globalOperationParameters;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Contact {
|
||||
|
||||
/**联系人**/
|
||||
private String name = "";
|
||||
/**联系人url**/
|
||||
private String url = "";
|
||||
/**联系人email**/
|
||||
private String email = "";
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
com.central.common.swagger2.SwaggerAutoConfiguration
|
||||
Reference in New Issue
Block a user