Commit 74952ec3 by linxu

refactor

parent d62ffd50
FROM openjdk:8-jre
ENV WORKING_DIR /opt/jboss
USER root
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
COPY target/login-1.0.0-SNAPSHOT.jar $WORKING_DIR/login.jar
RUN ls
RUN cd $WORKING_DIR && chown -R jboss:jboss login.jar
USER jboss
CMD ["/bin/sh", "-c", "java -Xmx128M -jar login.jar"]
#!/bin/bash
set -e
sudo docker build --rm -t login:1.0.0 .
...@@ -4,14 +4,14 @@ ...@@ -4,14 +4,14 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.keymobile.common</groupId> <groupId>com.keymobile.common</groupId>
<artifactId>login</artifactId> <artifactId>loginService</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>2.0.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.15.RELEASE</version> <version>2.0.4.RELEASE</version>
<relativePath/> <relativePath/>
</parent> </parent>
...@@ -19,25 +19,57 @@ ...@@ -19,25 +19,57 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version> <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>com.github.ulisesbocchio</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId> <artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>javax.interceptor</groupId>
<artifactId>spring-cloud-starter-kubernetes</artifactId> <artifactId>javax.interceptor-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-kubernetes-config</artifactId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.session</groupId> <groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId> <artifactId>spring-session-data-redis</artifactId>
...@@ -45,17 +77,29 @@ ...@@ -45,17 +77,29 @@
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId> <artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId> <artifactId>spring-boot-starter-security</artifactId>
</dependency> </dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>
...@@ -66,14 +110,36 @@ ...@@ -66,14 +110,36 @@
<version>5.1.6</version> <version>5.1.6</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
<dependency>
<groupId>com.kakawait</groupId>
<artifactId>cas-security-spring-boot-starter</artifactId>
<version>1.0.0-beta-1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.30</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId> <groupId>redis.clients</groupId>
<artifactId>jedis</artifactId> <artifactId>jedis</artifactId>
<version>2.9.0</version> <version>2.9.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>com.keymobile.authService</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>auth-common</artifactId>
<scope>test</scope> <scope>system</scope>
<systemPath>${project.basedir}/lib/auth-common-2.0.0.jar</systemPath>
<version>1.0.2</version>
</dependency> </dependency>
</dependencies> </dependencies>
...@@ -86,18 +152,34 @@ ...@@ -86,18 +152,34 @@
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-bom</artifactId>
<version>${spring-security.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
<repositories>
<repository>
<id>maven-snapshots</id>
<name>maven-snapshots</name>
<url>http://mgr-00:8081/repository/maven-public/</url>
</repository>
</repositories>
<build> <build>
<resources>
<resource>
<directory>lib</directory>
<targetPath>BOOT-INF/lib/</targetPath>
<includes>
<include>**/*.jar</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.yml</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
......
package com.keymobile.proxy; package com.keymobile.login;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
......
package com.keymobile.proxy.api; package com.keymobile.login.api;
public class Constants { public class Constants {
......
package com.keymobile.proxy.api; package com.keymobile.login.api;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
......
package com.keymobile.proxy.conf; package com.keymobile.login.conf;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.AuthenticationEntryPoint;
......
package com.keymobile.proxy.conf; package com.keymobile.login.conf;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
...@@ -8,7 +8,6 @@ import javax.servlet.ServletException; ...@@ -8,7 +8,6 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter;
@Component @Component
public class RESTAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { public class RESTAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
......
package com.keymobile.proxy.conf; package com.keymobile.login.conf;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.keymobile.proxy.api.Constants;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Component @Component
public class RESTAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { public class RESTAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
......
package com.keymobile.proxy.conf; package com.keymobile.login.conf;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
......
package com.keymobile.login.conf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConf {
/**
* 注入 RedisConnectionFactory
*/
@Autowired
RedisConnectionFactory redisConnectionFactory;
/**
* 实例化 RedisTemplate 对象
*
* @return
*/
@Bean
public RedisTemplate<String, Object> functionDomainRedisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
return redisTemplate;
}
/**
* 设置数据存入 redis 的序列化方式
*
* @param redisTemplate
* @param factory
*/
private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setConnectionFactory(factory);
}
/**
* 实例化 HashOperations 对象,可以使用 Hash 类型操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 实例化 ValueOperations 对象,可以使用 String 操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 实例化 ListOperations 对象,可以使用 List 操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 实例化 SetOperations 对象,可以使用 Set 操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 实例化 ZSetOperations 对象,可以使用 ZSet 操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}}
package com.keymobile.proxy.conf; package com.keymobile.login.conf;
import com.keymobile.auth.common.security.CustomizedUserDetailService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import javax.sql.DataSource;
@Configuration @Configuration
@ComponentScan("com.keymobile.auth.common.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter { public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String usersQuery = "select concat(user_name, ':', user_id, ':', user_dname), password, true \n" +
"from auth_user where user_name = ?";
private static final String rolesQuery = "select t1.user_name, concat(concat('ROLE_', t1.author_name), ':', GROUP_CONCAT(COALESCE(t2.domain_id, '*'))) as role_name \n" +
"from \n" +
" (select a.user_name, d.author_name\n" +
" from auth_user a, auth_user_roles b, auth_role_authors c, auth_author d\n" +
" where a.user_id = b.user_id and b.role_id = c.role_id and c.author_id = d.author_id\n" +
" and a.user_name = substring_index(?, ':', 1)) t1\n" +
" left join\n" +
" (select a.user_name, c.domain_id\n" +
" from auth_user a, auth_user_domains b, auth_domain c\n" +
" where a.user_id = b.user_id and b.domain_id = c.domain_id) t2\n" +
"on t1.user_name = t2.user_name \n" +
"group by t1.author_name";
@Autowired @Autowired
private DataSource dataSource; private CustomizedUserDetailService customUserDetailService;
@Autowired @Autowired
private RESTAuthenticationEntryPoint authenticationEntryPoint; private RESTAuthenticationEntryPoint authenticationEntryPoint;
@Autowired @Autowired
...@@ -40,13 +28,12 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { ...@@ -40,13 +28,12 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired @Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception { public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery) auth.userDetailsService(customUserDetailService).passwordEncoder(NoOpPasswordEncoder.getInstance());
.dataSource(dataSource).passwordEncoder(NoOpPasswordEncoder.getInstance());
} }
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll(); http.authorizeRequests().anyRequest().permitAll();
http.csrf().disable(); http.csrf().disable();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
http.formLogin().successHandler(authenticationSuccessHandler); http.formLogin().successHandler(authenticationSuccessHandler);
......
package com.keymobile.proxy.exception; package com.keymobile.login.exception;
import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
......
package com.keymobile.proxy.exception; package com.keymobile.login.exception;
import org.springframework.core.Ordered; import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
......
package com.keymobile.login.logging;
public interface LogConstants {
}
package com.keymobile.login.logging;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogManager {
public static void logTrace(String context, Throwable e, String message) {
Logger logger = LoggerFactory.getLogger(context);
if (logger.isTraceEnabled()) {
logger.trace(message, e);
}
}
public static void logTrace(String context, String message) {
logTrace(context, null, message);
}
public static void logDebug(String context, String message) {
Logger logger = LoggerFactory.getLogger(context);
if (logger.isDebugEnabled()) {
logger.debug(message);
}
}
public static void logInfo(String context, String message) {
Logger logger = LoggerFactory.getLogger(context);
if (logger.isInfoEnabled()) {
logger.info(message);
}
}
public static void logWarning(String context, Throwable e, String message) {
Logger logger = LoggerFactory.getLogger(context);
if (logger.isWarnEnabled()) {
logger.warn(message, e);
}
}
public static void logWarning(String context, String message) {
logWarning(context, null, message);
}
public static void logError(String context, Throwable e, String message) {
Logger logger = LoggerFactory.getLogger(context);
if (logger.isErrorEnabled()) {
logger.error(message, e);
}
}
public static void logError(String context, String message) {
logError(context, message);
}
}
package com.keymobile.login.logging;
import org.slf4j.MDC;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import javax.servlet.*;
import java.io.IOException;
@Component
public class MdcLogEnhancerFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
MDC.put("user", getUser());
MDC.put("session", getSession());
filterChain.doFilter(servletRequest, servletResponse);
}
private String getUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String userName = "NO_USER";
if (auth != null) {
userName = auth.getName();
}
return userName;
}
private String getSession() {
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
String session = "NO_SESSION";
if (attrs != null) {
session = attrs.getSessionId();
}
return session;
}
}
package com.keymobile.proxy.conf;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}
package com.keymobile.proxy.conf;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import redis.clients.jedis.JedisPoolConfig;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Administrator on 2019/2/28.
*/
@EnableRedisHttpSession
@Configuration
public class RedisClusterConfig {
@Value("${spring.redis.cluster.nodes}")
private String clusterNodes;
@Value("${spring.redis.cluster.max-redirects}")
private int maxRedirects;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.maxIdle}")
private int maxIdle;
@Value("${spring.redis.maxTotal}")
private int maxTotal;
@Value("${spring.redis.maxWaitMillis}")
private int maxWaitMillis;
@Value("${spring.redis.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.redis.numTestsPerEvictionRun}")
private int numTestsPerEvictionRun;
@Value("${spring.redis.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.redis.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.redis.testWhileIdle}")
private boolean testWhileIdle;
@Bean
public JedisPoolConfig getJedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// 最大空闲数
jedisPoolConfig.setMaxIdle(maxIdle);
// 连接池的最大数据库连接数
jedisPoolConfig.setMaxTotal(maxTotal);
// 最大建立连接等待时间
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
// 逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
// 每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
// 逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
jedisPoolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
// 是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
jedisPoolConfig.setTestOnBorrow(testOnBorrow);
// 在空闲时检查有效性, 默认false
jedisPoolConfig.setTestWhileIdle(testWhileIdle);
return jedisPoolConfig;
}
/**
* Redis集群的配置
* @return RedisClusterConfiguration
* @throws
*/
@Bean
public RedisClusterConfiguration redisClusterConfiguration(){
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
//Set<RedisNode> clusterNodes
String[] serverArray = clusterNodes.split(",");
Set<RedisNode> nodes = new HashSet<RedisNode>();
for(String ipPort:serverArray){
String[] ipAndPort = ipPort.split(":");
nodes.add(new RedisNode(ipAndPort[0].trim(),Integer.valueOf(ipAndPort[1])));
}
redisClusterConfiguration.setClusterNodes(nodes);
redisClusterConfiguration.setMaxRedirects(maxRedirects);
redisClusterConfiguration.setPassword(RedisPassword.of(password));
return redisClusterConfiguration;
}
/**
* @param
* @return
* @Description:redis连接工厂类
* @date 2018/10/25 19:45
*/
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
if (clusterNodes.split(",").length == 1) {
//非多节点集群
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(clusterNodes.split(":")[0]);
factory.setPort(Integer.valueOf(clusterNodes.split(":")[1]));
factory.setPassword(password);
factory.setTimeout(timeout);
return factory;
} else {
//集群模式
JedisConnectionFactory factory = new JedisConnectionFactory(redisClusterConfiguration(),getJedisPoolConfig());
factory.setDatabase(0);
factory.setTimeout(timeout);
factory.setUsePool(true);
return factory;
}
}
/**
* 实例化 RedisTemplate 对象
*
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
initDomainRedisTemplate(redisTemplate);
return redisTemplate;
}
/**
* 设置数据存入 redis 的序列化方式,并开启事务
* 使用默认的序列化会导致key乱码
*
*/
private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
//如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!
redisTemplate.setKeySerializer(new StringRedisSerializer());
//这个地方有一个问题,这种序列化器会将value序列化成对象存储进redis中,如果
//你想取出value,然后进行自增的话,这种序列化器是不可以的,因为对象不能自增;
//需要改成StringRedisSerializer序列化器。
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setEnableTransactionSupport(false);
redisTemplate.setConnectionFactory(jedisConnectionFactory());
}
@Bean
public static ConfigureRedisAction configureRedisAction(){
return ConfigureRedisAction.NO_OP;
}
}
server:
port: 8764
spring:
application:
name: auth
session:
store-type: redis
redis:
cluster:
nodes: 192.168.0.192:6379
max-redirects: 6
timeout: 10000
maxIdle: 300
maxTotal: 1000
maxWaitMillis: 1000
minEvictableIdleTimeMillis: 300000
numTestsPerEvictionRun: 1024
timeBetweenEvictionRunsMillis: 30000
testOnBorrow: true
testWhileIdle: true
password:
datasource:
url: jdbc:mysql://192.168.0.192:3306/dev0?autoReconnect=true
username: test
password: test
driver-class-name: com.mysql.jdbc.Driver
cloud:
kubernetes:
enabled: false
eureka:
client:
registerWithEureka: true
region: default
registryFetchIntervalSeconds: 5
serviceUrl:
defaultZone: http://dev-vm-12:8081/eureka/
logging:
level:
org.springframework.security: info
server: server:
port: 8764 port: 8764
eureka:
client:
registerWithEureka: true
region: default
registryFetchIntervalSeconds: 5
serviceUrl:
defaultZone: http://192.168.0.111:8081/eureka/
instance:
prefer-ip-address: false
hostname: 192.168.0.143
spring: spring:
application:
name: auth
session: session:
store-type: redis store-type: redis
redis: redis:
...@@ -12,26 +21,16 @@ spring: ...@@ -12,26 +21,16 @@ spring:
host: 192.168.0.192 host: 192.168.0.192
port: 6379 port: 6379
datasource: datasource:
url: jdbc:mysql://192.168.0.192:test/dataSharing?autoReconnect=true driver-class-name: com.mysql.jdbc.Driver
username: root url: jdbc:mysql://192.168.0.192:3306/cgn2_dev?autoReconnect=true
password: dataSharing username: test
servlet: password: test
multipart:
max-file-size: 100Mb
max-request-size: 100Mb
eureka:
client:
registerWithEureka: false
region: default
registryFetchIntervalSeconds: 5
serviceUrl:
defaultZone: http://localhost:8081/eureka/
zuul: security:
prefix: /api authUser: root
sensitive-headers: authPwd: pwd
permit: false
allowRootLogin: true
logging: logging:
level: config: classpath:logback-custom.xml
org.springframework.security: DEBUG \ No newline at end of file
\ No newline at end of file
jasypt.encryptor.algorithm=PBEWithMD5AndDES
jasypt.encryptor.iv-generator-classname=org.jasypt.iv.NoIvGenerator
\ No newline at end of file
...@@ -2,4 +2,7 @@ spring: ...@@ -2,4 +2,7 @@ spring:
application: application:
name: auth name: auth
profiles: profiles:
active: dev active: local
\ No newline at end of file cloud:
config:
uri:
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<springProperty name="spring.datasource.url" source="spring.datasource.url"/>
<springProperty name="spring.datasource.username" source="spring.datasource.username"/>
<springProperty name="spring.datasource.password" source="spring.datasource.password"/>
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %X{user} %X{session} %-5level %logger{5} - %msg%n</pattern>
</encoder>
</appender>
<appender name="db" class="ch.qos.logback.classic.db.DBAppender">
<connectionSource
class="ch.qos.logback.core.db.DriverManagerConnectionSource">
<driverClass>com.mysql.jdbc.Driver</driverClass>
<url>${spring.datasource.url}</url>
<user>${spring.datasource.username}</user>
<password>${spring.datasource.password}</password>
</connectionSource>
</appender>
<logger name="auth.AUDIT">
<appender-ref ref="db" />
</logger>
<root level="INFO">
<appender-ref ref="stdout" />
</root>
</configuration>
package com.keymobile.proxy;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProxyApplicationTests {
@Test
public void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment