提交 bf66e8d9 authored 作者: 黄夏豪's avatar 黄夏豪

项目完善

上级 c960df7b
...@@ -152,11 +152,11 @@ ...@@ -152,11 +152,11 @@
</dependency> </dependency>
<!--eureka:注册到注册中心--> <!--eureka:注册到注册中心-->
<dependency> <!-- <dependency>-->
<groupId>org.springframework.cloud</groupId> <!-- <groupId>org.springframework.cloud</groupId>-->
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <!-- <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>-->
<!--<version>2.0.1.RELEASE</version>--> <!-- &lt;!&ndash;<version>2.0.1.RELEASE</version>&ndash;&gt;-->
</dependency> <!-- </dependency>-->
<!--admin客户端依赖--> <!--admin客户端依赖-->
<dependency> <dependency>
<groupId>de.codecentric</groupId> <groupId>de.codecentric</groupId>
......
...@@ -6,12 +6,8 @@ import com.example.personnelmanager.dao.SimpleJpaRepositoryImpl; ...@@ -6,12 +6,8 @@ import com.example.personnelmanager.dao.SimpleJpaRepositoryImpl;
import gnu.io.CommPortIdentifier; import gnu.io.CommPortIdentifier;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter; import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
...@@ -19,17 +15,14 @@ import org.springframework.scheduling.annotation.EnableAsync; ...@@ -19,17 +15,14 @@ import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2; import springfox.documentation.swagger2.annotations.EnableSwagger2;
import javax.persistence.EntityListeners;
/** /**
* springBoot启动类 * springBoot启动类
* *
* @author Huangxiahao * @author Huangxiahao
*/ */
@EnableFeignClients
@EnableAsync @EnableAsync
@EnableScheduling @EnableScheduling
@EnableDiscoveryClient //@EnableDiscoveryClient
@SpringBootApplication @SpringBootApplication
@EnableSwagger2 @EnableSwagger2
@EnableJpaAuditing @EnableJpaAuditing
...@@ -39,9 +32,11 @@ public class PersonnelmanagerApplication extends SpringBootServletInitializer { ...@@ -39,9 +32,11 @@ public class PersonnelmanagerApplication extends SpringBootServletInitializer {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(PersonnelmanagerApplication.class, args); SpringApplication.run(PersonnelmanagerApplication.class, args);
//todo 初始化一个初始企业 初始化一个admin 初始化一个节点
System.out.println("程序运行成功"); System.out.println("程序运行成功");
DateCenterUtil dateCenterUtil = SpringUtils.getBean("dateCenterUtil"); DateCenterUtil dateCenterUtil = SpringUtils.getBean("dateCenterUtil");
dateCenterUtil.sendDateToCenter(); dateCenterUtil.sendDateToCenter();
// dateCenterUtil.initUser();
} }
@Bean @Bean
......
...@@ -18,6 +18,7 @@ package com.example.personnelmanager.common.authencation.filter; ...@@ -18,6 +18,7 @@ package com.example.personnelmanager.common.authencation.filter;
import com.example.personnelmanager.common.authencation.token.JwtAuthencationToken; import com.example.personnelmanager.common.authencation.token.JwtAuthencationToken;
import com.example.personnelmanager.common.exception.GlobalException; import com.example.personnelmanager.common.exception.GlobalException;
import com.example.personnelmanager.common.utils.CipherUtil;
import com.example.personnelmanager.common.utils.JwtUtils; import com.example.personnelmanager.common.utils.JwtUtils;
import com.example.personnelmanager.common.utils.RsaUtils; import com.example.personnelmanager.common.utils.RsaUtils;
import com.example.personnelmanager.common.utils.UTF8ToString; import com.example.personnelmanager.common.utils.UTF8ToString;
...@@ -26,6 +27,7 @@ import com.google.gson.JsonObject; ...@@ -26,6 +27,7 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
...@@ -59,10 +61,9 @@ public class CustomJwtAuthenticationFilter extends ...@@ -59,10 +61,9 @@ public class CustomJwtAuthenticationFilter extends
*/ */
String jwtFilePath; String jwtFilePath;
public CustomJwtAuthenticationFilter(String jwtFilePath) { public CustomJwtAuthenticationFilter() {
//设置用户接口的路径以及访问方式 //设置用户接口的路径以及访问方式
super(new AntPathRequestMatcher("/api/user/login", "GET")); super(new AntPathRequestMatcher("/api/user/login", "GET"));
this.jwtFilePath = jwtFilePath;
} }
/*** /***
...@@ -81,7 +82,7 @@ public class CustomJwtAuthenticationFilter extends ...@@ -81,7 +82,7 @@ public class CustomJwtAuthenticationFilter extends
//通过请求头获取jwt凭证中的用户信息 //通过请求头获取jwt凭证中的用户信息
userByJwt = getuserbyjwt(request); userByJwt = getuserbyjwt(request);
authRequest = new JwtAuthencationToken( authRequest = new JwtAuthencationToken(
userByJwt.getUsername().trim()); userByJwt);
//为用于验证的用户注入session信息 //为用于验证的用户注入session信息
setDetails(request, authRequest); setDetails(request, authRequest);
//进行验证 //进行验证
...@@ -89,10 +90,6 @@ public class CustomJwtAuthenticationFilter extends ...@@ -89,10 +90,6 @@ public class CustomJwtAuthenticationFilter extends
} else { } else {
throw new GlobalException("未设置token"); throw new GlobalException("未设置token");
} }
//以下为测试代码
// JwtAuthencationToken authRequest ;
// authRequest = new JwtAuthencationToken("admin");
// return getAuthenticationManager().authenticate(authRequest);
} }
...@@ -114,28 +111,21 @@ public class CustomJwtAuthenticationFilter extends ...@@ -114,28 +111,21 @@ public class CustomJwtAuthenticationFilter extends
* @Return : com.example.personnelmanager.entity.User * @Return : com.example.personnelmanager.entity.User
*/ */
public User getuserbyjwt(HttpServletRequest request) { public User getuserbyjwt(HttpServletRequest request) {
String rsaPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJcz+ZlYYNQVfAap+Qyj7A7izqRVcDYLInB35mKe3Vqo/dN/0bDSTLKibu3wf4DigTszxZ7I7B2jkWrIB0V4RX56clWWGwfneLLTM9WDcNav6QDpt7ioBCdMdkJiOGgGQ9nIBHZI1WQAeRhjffNELa2pi3VffiSEoODEQ61+N3DfAgMBAAECgYBBBanlptrk+WQ/nWKra+a8tA53HwLFSt6BjR429Oht71RQWpw7NQSkoTOhARZjv4QhiG8IjJD1YfzL9b8iwcjoI8Na+aZN3Ugx5tc+PZzAXA22S4EXVl8RBlLOwhak7R37Ildikm2pBY2UC1iI/Uh2tK4jIAr6i+cYlc6DAo66sQJBANxolsi7WNvmgZSNUPF0HYF1kY9WylmFaDWpH5lcbZxj0EmEkaM+T54P6iYj2ivTHsSJIPSi/T3Ss/oEmLTNKNcCQQCvnoRgj2K2GEpORdLHye3CKn3LOCW/f8dCuwggITsGz7rdUUJhjX4RopCPXt92SDED8JdqZFFe3JhZODvhqU85AkAv99cxEozxNsZmxSajlejB/wtRzcq2FvGqFAebgeEdEyAGkAJ+K5Z6SO5lpJHbzdO5ZDq24y4IIW4n8I4ncyr7AkADbhUnzaUf6VmKLdLwFAGQyUOrtG0IUHaT1xNRjVSZzXTY3b1uKlVMAuDP7ApxRPewHALZERyFvck79N02ixgBAkEAzjHNWU5lCbQeqgHF8jwHMN/08c3tMZvJRRyFjFiExiNn1Qj2iqRd1FiyVt1nSJ8jeDbFxPn6McDk5vAZslSRvQ==";
String signPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPepqt/IABL0roOaP4PWFnSBBfQlHae1ojeSxZMK7rcPhXRjg/xahs/qtLe4gblJ1dnUOWwZhcky2Q+jyHCaeSO8TWqnH/+OWsYQDHT7jSzYj9GETqQaxmIm2b919RITfBwsh4lTnar9ZUPvJD6HGrfZUY7RvuMapDwRSo8UUy8wIDAQAB";
String jwt = request.getHeader("jwt"); String jwt = request.getHeader("jwt");
logger.info("接收到的头部信息:"+jwt);
jwt = jwt.replace("\"","");
logger.info("处理过后的头部信息:"+jwt);
PublicKey publicKey = null;
try { try {
publicKey = RsaUtils.getPublicKey(jwtFilePath); String decrypt = CipherUtil.decrypt(jwt, CipherUtil.string2PrivateKey(rsaPrivateKey));
} catch (Exception e) { Jws<Claims> claimsJws = Jwts.parser().setSigningKey(CipherUtil.string2PublicKey(signPublicKey)).parseClaimsJws(decrypt);
e.printStackTrace();
}
try {
logger.info("公钥为:"+publicKey);
Jws<Claims> claimsJws = JwtUtils.parseToken(publicKey, jwt);
logger.info("接收到的用户信息为:"+claimsJws.getBody()); logger.info("接收到的用户信息为:"+claimsJws.getBody());
User userRight = new User(); User userRight = new User();
Claims body = claimsJws.getBody(); Claims body = claimsJws.getBody();
userRight.setUsername((String) body.get("username")); userRight.setUsername((String) body.get("username"));
userRight.setPhone((String) body.get("phone"));
return userRight; return userRight;
}catch (Exception e){ }catch (Exception e){
logger.error("用户凭证无效"); logger.error("用户凭证无效");
throw new UsernameNotFoundException("用户凭证无效"); throw new UsernameNotFoundException("用户凭证无效");
} }
} }
} }
...@@ -2,6 +2,8 @@ package com.example.personnelmanager.common.authencation.provider; ...@@ -2,6 +2,8 @@ package com.example.personnelmanager.common.authencation.provider;
import com.example.personnelmanager.common.authencation.token.JwtAuthencationToken; import com.example.personnelmanager.common.authencation.token.JwtAuthencationToken;
import com.example.personnelmanager.common.authencation.checks.DefaultPreAuthenticationChecks; import com.example.personnelmanager.common.authencation.checks.DefaultPreAuthenticationChecks;
import com.example.personnelmanager.entity.User;
import com.example.personnelmanager.service.impl.UserDetailsServiceImpl;
import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
...@@ -25,14 +27,14 @@ import org.springframework.util.Assert; ...@@ -25,14 +27,14 @@ import org.springframework.util.Assert;
@Component @Component
public class JwtAuthenticationProvider implements AuthenticationProvider { public class JwtAuthenticationProvider implements AuthenticationProvider {
private final UserDetailsService userDetailsService; private final UserDetailsServiceImpl userDetailsService;
/** /**
* 用户可用性检查类 * 用户可用性检查类
*/ */
private final UserDetailsChecker preAuthenticationChecks = new DefaultPreAuthenticationChecks(); private final UserDetailsChecker preAuthenticationChecks = new DefaultPreAuthenticationChecks();
public JwtAuthenticationProvider(UserDetailsService userDetailsService) { public JwtAuthenticationProvider(UserDetailsServiceImpl userDetailsService) {
this.userDetailsService = userDetailsService; this.userDetailsService = userDetailsService;
} }
...@@ -47,8 +49,8 @@ public class JwtAuthenticationProvider implements AuthenticationProvider { ...@@ -47,8 +49,8 @@ public class JwtAuthenticationProvider implements AuthenticationProvider {
Assert.isInstanceOf(JwtAuthencationToken.class, authentication, Assert.isInstanceOf(JwtAuthencationToken.class, authentication,
"错误的凭证"); "错误的凭证");
String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
: authentication.getName(); : ((User)authentication.getPrincipal()).getUsername();
UserDetails user = retrieveUser(username); UserDetails user = retrieveUser(username,((User)authentication.getPrincipal()).getPhone());
preAuthenticationChecks.check(user); preAuthenticationChecks.check(user);
return createSuccessAuthentication(user,authentication,user); return createSuccessAuthentication(user,authentication,user);
} }
...@@ -70,8 +72,8 @@ public class JwtAuthenticationProvider implements AuthenticationProvider { ...@@ -70,8 +72,8 @@ public class JwtAuthenticationProvider implements AuthenticationProvider {
* @param username * @param username
* @Return : org.springframework.security.core.userdetails.UserDetails * @Return : org.springframework.security.core.userdetails.UserDetails
*/ */
protected final UserDetails retrieveUser(String username) { protected final UserDetails retrieveUser(String username,String phone) {
UserDetails loadedUser = userDetailsService.loadUserByUsername(username); UserDetails loadedUser = userDetailsService.loadUserByUsername(username,phone);
if (loadedUser == null) { if (loadedUser == null) {
throw new InternalAuthenticationServiceException( throw new InternalAuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation"); "UserDetailsService returned null, which is an interface contract violation");
......
...@@ -35,6 +35,8 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro ...@@ -35,6 +35,8 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro
*/ */
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
private final UserDetailsService userDetailsService; private final UserDetailsService userDetailsService;
/** /**
......
...@@ -73,4 +73,6 @@ public class JwtAuthencationToken extends AbstractAuthenticationToken { ...@@ -73,4 +73,6 @@ public class JwtAuthencationToken extends AbstractAuthenticationToken {
credentials = null; credentials = null;
} }
} }
package com.example.personnelmanager.common.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 描述:跨域处理
*
* @author HuangXiahao
* @version V1.0
* @class CorsConfig
* @packageName com.example.demo.common.config
* @data 2020/4/21
**/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
\ No newline at end of file
package com.example.personnelmanager.common.config; package com.example.personnelmanager.common.config;
import com.example.personnelmanager.common.authencation.filter.JWTAuthorizationFilter;
import com.example.personnelmanager.common.authencation.provider.JwtAuthenticationProvider; import com.example.personnelmanager.common.authencation.provider.JwtAuthenticationProvider;
import com.example.personnelmanager.common.authencation.provider.UsernamePasswordAuthenticationProvider; import com.example.personnelmanager.common.authencation.provider.UsernamePasswordAuthenticationProvider;
import com.example.personnelmanager.common.authencation.filter.CustomJwtAuthenticationFilter; import com.example.personnelmanager.common.authencation.filter.CustomJwtAuthenticationFilter;
...@@ -23,6 +24,7 @@ import org.springframework.security.web.AuthenticationEntryPoint; ...@@ -23,6 +24,7 @@ import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.ServletOutputStream; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
...@@ -60,8 +62,8 @@ public class SecurityWebConfig extends WebSecurityConfigurerAdapter { ...@@ -60,8 +62,8 @@ public class SecurityWebConfig extends WebSecurityConfigurerAdapter {
/** /**
* jwt公钥存储路径 * jwt公钥存储路径
**/ **/
@Value("${file.jwtFilePath}") // @Value("${file.jwtFilePath}")
String jwtFilePath; // String jwtFilePath;
public SecurityWebConfig(JwtAuthenticationProvider jwtAuthenticationProvider, UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider) { public SecurityWebConfig(JwtAuthenticationProvider jwtAuthenticationProvider, UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider) {
this.jwtAuthenticationProvider = jwtAuthenticationProvider; this.jwtAuthenticationProvider = jwtAuthenticationProvider;
...@@ -90,11 +92,11 @@ public class SecurityWebConfig extends WebSecurityConfigurerAdapter { ...@@ -90,11 +92,11 @@ public class SecurityWebConfig extends WebSecurityConfigurerAdapter {
"/swagger-ui.html", "/swagger-ui.html",
"/webjars/**").permitAll() "/webjars/**").permitAll()
.anyRequest() .anyRequest()
.permitAll() .authenticated()
.and() .and()
.logout() .logout()
//登出接口权限开放 //登出接口权限开放
.logoutUrl("/user/logout").permitAll() .logoutUrl("/api/user/logout").permitAll()
.and() .and()
.sessionManagement() .sessionManagement()
.and() .and()
...@@ -104,7 +106,8 @@ public class SecurityWebConfig extends WebSecurityConfigurerAdapter { ...@@ -104,7 +106,8 @@ public class SecurityWebConfig extends WebSecurityConfigurerAdapter {
//添加自定义用户验证拦截器至UsernamePasswordAuthenticationFilter的位置 //添加自定义用户验证拦截器至UsernamePasswordAuthenticationFilter的位置
http.addFilterAt(customUsernamePasswordAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class); http.addFilterAt(customUsernamePasswordAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class);
http.addFilterAt(customJwtUsernamePasswordAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class); // http.addFilterAt(customJwtUsernamePasswordAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class);
// http.addFilterAt(new JWTAuthorizationFilter(authenticationManager()), BasicAuthenticationFilter.class);
} }
/*** /***
...@@ -128,7 +131,7 @@ public class SecurityWebConfig extends WebSecurityConfigurerAdapter { ...@@ -128,7 +131,7 @@ public class SecurityWebConfig extends WebSecurityConfigurerAdapter {
*/ */
@Bean @Bean
CustomJwtAuthenticationFilter customJwtUsernamePasswordAuthenticationFilter() throws Exception { CustomJwtAuthenticationFilter customJwtUsernamePasswordAuthenticationFilter() throws Exception {
CustomJwtAuthenticationFilter filter = new CustomJwtAuthenticationFilter(jwtFilePath); CustomJwtAuthenticationFilter filter = new CustomJwtAuthenticationFilter();
filter.setAuthenticationManager(authenticationManager()); filter.setAuthenticationManager(authenticationManager());
filter.setAuthenticationSuccessHandler(new CustomAuthenticationSuccessHandler()); filter.setAuthenticationSuccessHandler(new CustomAuthenticationSuccessHandler());
filter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler()); filter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler());
......
...@@ -2,6 +2,7 @@ package com.example.personnelmanager.common.config; ...@@ -2,6 +2,7 @@ package com.example.personnelmanager.common.config;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
...@@ -19,6 +20,20 @@ public class WebMvcConfig implements WebMvcConfigurer { ...@@ -19,6 +20,20 @@ public class WebMvcConfig implements WebMvcConfigurer {
@Value("${file.imagePath}") @Value("${file.imagePath}")
String imagePath; String imagePath;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("PUT", "DELETE", "GET", "POST", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("access-control-allow-headers",
"access-control-allow-methods",
"access-control-allow-origin",
"access-control-max-age",
"X-Frame-Options")
.allowCredentials(true).maxAge(3600);
}
/** /**
* 静态资源配置 * 静态资源配置
* *
......
package com.example.personnelmanager.common.utils;
import com.example.personnelmanager.common.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
/**
* @author HuangXiahao
* @version V1.0
* @class encryptionUtil
* @packageName com.tykj.support.misc.util
**/
@Slf4j
public class CipherUtil {
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
private static String getPublicKeyString(PublicKey publicKey) {
return new String(Base64.getEncoder().encode(publicKey.getEncoded()));
}
private static String getPrivateKeyString(PrivateKey privateKey) {
return new String(Base64.getEncoder().encode(privateKey.getEncoded()));
}
/**
* 获取私钥
*
* @param str 私钥字符串
* @return
*/
public static PrivateKey string2PrivateKey(String str) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] decodedKey = Base64.getDecoder().decode(str.getBytes());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
return keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new GlobalException("解析私钥错误");
}
}
/**
* 获取公钥
*
* @param str 公钥字符串
* @return
*/
public static PublicKey string2PublicKey(String str) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] decodedKey = Base64.getDecoder().decode(str.getBytes());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
return keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new GlobalException("解析公钥错误");
}
}
/**
* RSA加密
*
* @param data 待加密数据
* @param publicKey 公钥
* @return
*/
public static String encrypt(String data, PublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = data.getBytes().length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
}
out.write(cache);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
// 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
// 加密后的字符串
return Base64.getEncoder().encodeToString(encryptedData);
} catch (NoSuchAlgorithmException | IOException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
throw new GlobalException("加密失败");
}
}
/**
* RSA解密
*
* @param data 待解密数据
* @param privateKey 私钥
* @return
*/
public static String decrypt(String data, PrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] dataBytes = Base64.getDecoder().decode(data);
int inputLen = dataBytes.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
}
out.write(cache);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
// 解密后的内容
return new String(decryptedData, "UTF-8");
} catch (NoSuchAlgorithmException | IOException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
throw new GlobalException("加密失败");
}
}
}
...@@ -45,7 +45,7 @@ public class DateCenterJsonUtil { ...@@ -45,7 +45,7 @@ public class DateCenterJsonUtil {
*/ */
public String initAllPeopleJsonStr(List<People> allPeople){ public String initAllPeopleJsonStr(List<People> allPeople){
JsonObject jsonObject = new JsonObject(); JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("tableId",1308221225377472514L); jsonObject.addProperty("tableId",1320331389656211458L);
jsonObject.addProperty("primaryKeyName","people_id"); jsonObject.addProperty("primaryKeyName","people_id");
JsonArray jsonElements = new JsonArray(); JsonArray jsonElements = new JsonArray();
allPeople.forEach(people -> { allPeople.forEach(people -> {
...@@ -64,6 +64,16 @@ public class DateCenterJsonUtil { ...@@ -64,6 +64,16 @@ public class DateCenterJsonUtil {
jsonElementPeopleData.addProperty("post_id", people.getPeoplePosts().get(0).getPost().getPostId()); jsonElementPeopleData.addProperty("post_id", people.getPeoplePosts().get(0).getPost().getPostId());
jsonElementPeopleData.addProperty("node_id", people.getPeoplePosts().get(0).getPost().getOrganizationNode().getNodeId()); jsonElementPeopleData.addProperty("node_id", people.getPeoplePosts().get(0).getPost().getOrganizationNode().getNodeId());
} }
if (people.getSex()!=null){
jsonElementPeopleData.addProperty("sex", people.getSex());
}
if (people.getPhone()!=null){
jsonElementPeopleData.addProperty("phone", people.getPhone());
}
if (people.getCurrentResidence()!=null){
jsonElementPeopleData.addProperty("current_residence", people.getCurrentResidence());
}
jsonElementPeopleData.addProperty("delete_tag", people.getDeleteTag()); jsonElementPeopleData.addProperty("delete_tag", people.getDeleteTag());
jsonElementPeopleData.addProperty("icon",people.getIcon()); jsonElementPeopleData.addProperty("icon",people.getIcon());
jsonElementPeople.add("dataMap",jsonElementPeopleData); jsonElementPeople.add("dataMap",jsonElementPeopleData);
...@@ -96,14 +106,14 @@ public class DateCenterJsonUtil { ...@@ -96,14 +106,14 @@ public class DateCenterJsonUtil {
*/ */
public String initAllOrganizationNodeJsonStr(List<OrganizationNode> allNode){ public String initAllOrganizationNodeJsonStr(List<OrganizationNode> allNode){
JsonObject jsonObject = new JsonObject(); JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("tableId",1308222142906638337L); jsonObject.addProperty("tableId",1320331411160408065L);
jsonObject.addProperty("primaryKeyName","node_id"); jsonObject.addProperty("primaryKeyName","node_id");
JsonArray jsonElements = new JsonArray(); JsonArray jsonElements = new JsonArray();
allNode.forEach(node -> { allNode.forEach(node -> {
JsonObject jsonElementPeople = new JsonObject(); JsonObject jsonElementPeople = new JsonObject();
jsonElementPeople.addProperty("primaryKeyValue",node.getNodeId()); jsonElementPeople.addProperty("primaryKeyValue",node.getNodeId());
JsonObject jsonElementPeopleData = new JsonObject(); JsonObject jsonElementPeopleData = new JsonObject();
jsonElementPeopleData.addProperty("name",node.getNodeName()); jsonElementPeopleData.addProperty("node_name",node.getNodeName());
jsonElementPeopleData.addProperty("parent_node",node.getParentNode()); jsonElementPeopleData.addProperty("parent_node",node.getParentNode());
jsonElementPeopleData.addProperty("delete_tag",node.getDeleteTag()); jsonElementPeopleData.addProperty("delete_tag",node.getDeleteTag());
jsonElementPeople.add("dataMap",jsonElementPeopleData); jsonElementPeople.add("dataMap",jsonElementPeopleData);
...@@ -112,4 +122,49 @@ public class DateCenterJsonUtil { ...@@ -112,4 +122,49 @@ public class DateCenterJsonUtil {
jsonObject.add("data",jsonElements); jsonObject.add("data",jsonElements);
return jsonObject.toString(); return jsonObject.toString();
} }
/**
* People 生成Json字符串 向数据中心提交数据
* Json结构
* {
* "tableId": 1308221225377472514,
* "primaryKeyName": "people_id",
* "data": [
* {
* "primaryKeyValue": 1,
* "dataMap": {
* "node_id":1
* "name": "开发部",
* "parent_node": "1",
* "delete_tag":"0",
* }
* }
* ]
* }
* @param peoples
* @return
*/
public String initUserJsonStr(List<People> peoples){
JsonArray jsonArray = new JsonArray();
peoples.forEach(people -> {
JsonObject jsonObject = new JsonObject();
if (people.getIdCardNumber()!=null){
jsonObject.addProperty("idCard",people.getIdCardNumber());
}
if (people.getSex()!=null){
if (people.getSex().equals("男")){
jsonObject.addProperty("sex",0);
}else {
jsonObject.addProperty("sex",1);
}
}
jsonObject.addProperty("des",people.getName());
jsonObject.addProperty("name",people.getName());
jsonObject.addProperty("phone",people.getPhone());
jsonObject.addProperty("username",people.getName());
jsonArray.add(jsonObject);
});
return jsonArray.toString();
}
} }
...@@ -2,11 +2,22 @@ package com.example.personnelmanager.common.utils; ...@@ -2,11 +2,22 @@ package com.example.personnelmanager.common.utils;
import com.example.personnelmanager.dao.OrganizationNodeRepository; import com.example.personnelmanager.dao.OrganizationNodeRepository;
import com.example.personnelmanager.dao.PeopleRepository; import com.example.personnelmanager.dao.PeopleRepository;
import com.example.personnelmanager.dao.UserRepository;
import com.example.personnelmanager.entity.OrganizationNode; import com.example.personnelmanager.entity.OrganizationNode;
import com.example.personnelmanager.entity.People; import com.example.personnelmanager.entity.People;
import com.example.personnelmanager.entity.User;
import com.example.personnelmanager.entity.commonEntity.CustomOrder;
import com.example.personnelmanager.entity.commonEntity.CustomPage;
import com.example.personnelmanager.service.UserServer;
import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.Arrays;
import java.util.List; import java.util.List;
/** /**
...@@ -30,12 +41,48 @@ public class DateCenterUtil { ...@@ -30,12 +41,48 @@ public class DateCenterUtil {
@Autowired @Autowired
DateCenterJsonUtil jsonUtil; DateCenterJsonUtil jsonUtil;
@Autowired
UserServer userServer;
@Autowired
UserRepository userRepository;
public void sendDateToCenter(){ public void sendDateToCenter(){
// 将数据库中的人员数据存放到数据中心 // 将数据库中的人员数据存放到数据中心
List<People> allPeople = peopleRepository.findAll(); List<People> allPeople = peopleRepository.findAll();
httpClientUtil.post("http://124.70.194.194:8090/opt/data", jsonUtil.initAllPeopleJsonStr(allPeople), "utf-8"); httpClientUtil.post("http://124.70.194.194:8090/opt/data", jsonUtil.initAllPeopleJsonStr(allPeople), "utf-8");
// 将数据库中的部门信息存放到数据中心 // 将数据库中的部门信息存放到数据中心
List<OrganizationNode> allNode = organizationNodeRepository.findAll(); List<OrganizationNode> allNode = organizationNodeRepository.findAll();
httpClientUtil.post("http://124.70.194.194:8090/opt/data", jsonUtil.initAllOrganizationNodeJsonStr(allNode), "utf-8"); httpClientUtil.post("http://124.70.194.194:8090/opt/data", jsonUtil.initAllOrganizationNodeJsonStr(allNode), "utf-8");
}; };
public void initUser(){
List<People> all = peopleRepository.findAll();
//初始化登录中心的用户
// httpClientUtil.post("http://127.0.0.1:12346/user/addUserList", jsonUtil.initUserJsonStr(all), "utf-8");
//初始化本系统用户
for (int i = 0; i < all.size(); i++) {
People people = all.get(i);
User user = new User();
user.setUsername(people.getName());
//判断用户名字是否在数据库中重复,如果重复则为用户名后面加上对应的重复次数,例如张三01
PredicateBuilder<User> and = Specifications.and();
and.eq("name",user.getName());
CustomPage customPage = new CustomPage();
customPage.setOrders(Arrays.asList(new CustomOrder("name", Sort.Direction.DESC)));
Page<User> users = userRepository.findAll(and.build(), customPage.getPageable());
if (users.getContent().size()>0){
User userRepeat = users.getContent().get(0);
user.setUsername(user.getName()+(userRepeat.getRepeatsNum()+1));
}
user.setAdministrator(false);
user.setCreateDate(Instant.now());
user.setName(people.getName());
user.setPassword("qwer1234");
user.setEnterprise(people.getEnterprise());
user.setPhone(people.getPhone());
userServer.addEntity(user);
}
}
} }
package com.example.personnelmanager.common.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import java.security.PrivateKey;
import java.util.Map;
/**
* @author HuangXiahao
* @version V1.0
* @class jwtUtil
* @packageName com.tykj.support.misc.util
**/
public class JwtUtil {
public static String generateToken(Map<String,Object> payloadMap, int expireMinutes, PrivateKey privateKey) {
return Jwts.builder()
.setClaims(payloadMap)
.setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
.signWith(SignatureAlgorithm.RS256, privateKey)
.compact();
}
public static String generateToken(Claims claims, int expireMinutes, PrivateKey privateKey) {
return Jwts.builder()
.setClaims(claims)
.setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
.signWith(SignatureAlgorithm.RS256, privateKey)
.compact();
}
}
...@@ -7,7 +7,8 @@ import java.io.IOException; ...@@ -7,7 +7,8 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
public class ResponseEntityUtil { public class ResponseEntityUtil {
public static String entityToString(CloseableHttpResponse response,String encode) throws IOException {
public static String entityToString(CloseableHttpResponse response,String encode) {
EntityThread entityThread = new EntityThread(response,encode); EntityThread entityThread = new EntityThread(response,encode);
entityThread.start(); entityThread.start();
try { try {
...@@ -22,6 +23,7 @@ public class ResponseEntityUtil { ...@@ -22,6 +23,7 @@ public class ResponseEntityUtil {
} }
return result; return result;
} }
static class EntityThread extends Thread{ static class EntityThread extends Thread{
CloseableHttpResponse response; CloseableHttpResponse response;
......
...@@ -76,41 +76,7 @@ public class RsaUtils { ...@@ -76,41 +76,7 @@ public class RsaUtils {
} }
/**
* 根据密文,生存rsa公钥和私钥,并写入指定文件
*
* @param publicKeyFilename 公钥文件路径
* @param privateKeyFilename 私钥文件路径
* @param secret 生成密钥的密文
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(secret.getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// 获取公钥并写出
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
writeFile(publicKeyFilename, publicKeyBytes);
// 获取私钥并写出
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
writeFile(privateKeyFilename, privateKeyBytes);
}
public static void test(String pubKeyStr) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
java.security.spec.X509EncodedKeySpec bobPubKeySpec = new java.security.spec.X509EncodedKeySpec(
new BASE64Decoder().decodeBuffer(pubKeyStr));
// RSA对称加密算法
java.security.KeyFactory keyFactory;
keyFactory = java.security.KeyFactory.getInstance("RSA");
// 取公钥匙对象
PublicKey publicKey = keyFactory.generatePublic(bobPubKeySpec);
FileOutputStream fsPubkey = new FileOutputStream("G:/other/rsa.pub");
fsPubkey.write(publicKey.getEncoded());
fsPubkey.close();
}
/** /**
* 向目标路径写入文件 * 向目标路径写入文件
......
package com.example.personnelmanager.controller; //package com.example.personnelmanager.controller;
//
import com.alibaba.fastjson.JSONObject; //import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference; //import com.alibaba.fastjson.TypeReference;
import com.example.personnelmanager.common.utils.DownloadFile; //import com.example.personnelmanager.common.utils.DownloadFile;
import com.example.personnelmanager.common.utils.ExceptionMessage; //import com.example.personnelmanager.common.utils.ExceptionMessage;
import com.example.personnelmanager.dao.CertificateRepository; //import com.example.personnelmanager.dao.CertificateRepository;
import com.example.personnelmanager.entity.Certificate; //import com.example.personnelmanager.entity.Certificate;
import org.apache.commons.logging.Log; //import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; //import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; //import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.parameters.P; //import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*; //import org.springframework.web.bind.annotation.*;
//
import javax.validation.Valid; //import javax.validation.Valid;
import javax.validation.constraints.NotEmpty; //import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull; //import javax.validation.constraints.NotNull;
import java.io.*; //import java.io.*;
import java.util.HashMap; //import java.util.HashMap;
import java.util.Map; //import java.util.Map;
//
/** ///**
* @author HuangXiahao // * @author HuangXiahao
* @version V1.0 // * @version V1.0
* @class JwtController // * @class JwtController
* @packageName com.example.personnelmanager.controller // * @packageName com.example.personnelmanager.controller
* @data 2020/6/11 // * @data 2020/6/11
**/ // **/
@RestController //@RestController
public class JwtController { //public class JwtController {
//
protected final Log logger = LogFactory.getLog(getClass()); // protected final Log logger = LogFactory.getLog(getClass());
//
//
/** // /**
* Jwt公钥保存路径 // * Jwt公钥保存路径
*/ // */
@Value("${file.jwtFilePath}") // @Value("${file.jwtFilePath}")
String jwtFilePath; // String jwtFilePath;
//
@RequestMapping(value = "/acceptSignature",method = RequestMethod.POST) // @RequestMapping(value = "/acceptSignature",method = RequestMethod.POST)
public Map acceptSignature(@RequestBody String s){ // public Map acceptSignature(@RequestBody String s){
logger.info("接收到的公钥信息:"+s); // logger.info("接收到的公钥信息:"+s);
JSONObject jsonObject = JSONObject.parseObject(s); // JSONObject jsonObject = JSONObject.parseObject(s);
try { // try {
saveFile(jsonObject.getString("publicKey")); // saveFile(jsonObject.getString("publicKey"));
Map result = new HashMap(); // Map result = new HashMap();
result.put("msg"," 上传成功"); // result.put("msg"," 上传成功");
result.put("code",200); // result.put("code",200);
logger.info("公钥信息保存成功"); // logger.info("公钥信息保存成功");
return result; // return result;
} catch (Exception e) { // } catch (Exception e) {
e.printStackTrace(); // e.printStackTrace();
Map result = new HashMap(); // Map result = new HashMap();
result.put("msg","接收签名信息失败"); // result.put("msg","接收签名信息失败");
result.put("code",500); // result.put("code",500);
result.put("data","接收签名信息失败"+ ExceptionMessage.getStackTraceInfo(e)); // result.put("data","接收签名信息失败"+ ExceptionMessage.getStackTraceInfo(e));
logger.info("公钥信息接收成功"); // logger.info("公钥信息接收成功");
return result; // return result;
} // }
} // }
//
void saveFile(String publicKey){ // void saveFile(String publicKey){
try { // try {
File file = new File(jwtFilePath); // File file = new File(jwtFilePath);
PrintWriter printWriter = new PrintWriter(new FileOutputStream(file)); // PrintWriter printWriter = new PrintWriter(new FileOutputStream(file));
printWriter.write(publicKey); // printWriter.write(publicKey);
printWriter.flush(); // printWriter.flush();
printWriter.close(); // printWriter.close();
} catch (FileNotFoundException e) { // } catch (FileNotFoundException e) {
e.printStackTrace(); // e.printStackTrace();
} catch (IOException e) { // } catch (IOException e) {
e.printStackTrace(); // e.printStackTrace();
} // }
} // }
//
//}
}
...@@ -8,6 +8,7 @@ import com.example.personnelmanager.entity.commonEntity.ResultObj; ...@@ -8,6 +8,7 @@ import com.example.personnelmanager.entity.commonEntity.ResultObj;
import com.example.personnelmanager.entity.vo.PeopleVo; import com.example.personnelmanager.entity.vo.PeopleVo;
import com.example.personnelmanager.entity.vo.pageableVo.PeoplePageableVo; import com.example.personnelmanager.entity.vo.pageableVo.PeoplePageableVo;
import com.example.personnelmanager.service.CertificateService; import com.example.personnelmanager.service.CertificateService;
import com.example.personnelmanager.service.PeoplePostService;
import com.example.personnelmanager.service.PeopleService; import com.example.personnelmanager.service.PeopleService;
import io.swagger.models.auth.In; import io.swagger.models.auth.In;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
...@@ -15,7 +16,12 @@ import org.apache.poi.ss.usermodel.Row; ...@@ -15,7 +16,12 @@ import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
...@@ -24,15 +30,14 @@ import org.springframework.web.bind.annotation.*; ...@@ -24,15 +30,14 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.Instant; import java.time.Instant;
import java.util.Calendar; import java.util.*;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
/** /**
* @author HuangXiahao * @author HuangXiahao
...@@ -58,6 +63,9 @@ public class PeopleController { ...@@ -58,6 +63,9 @@ public class PeopleController {
final CertificateService certificateService; final CertificateService certificateService;
@Autowired
PeoplePostService peoplePostService;
public PeopleController(PeopleService peopleService, CertificateService certificateService) { public PeopleController(PeopleService peopleService, CertificateService certificateService) {
this.peopleService = peopleService; this.peopleService = peopleService;
this.certificateService = certificateService; this.certificateService = certificateService;
...@@ -70,35 +78,89 @@ public class PeopleController { ...@@ -70,35 +78,89 @@ public class PeopleController {
} }
@RequestMapping(value = "/excel",method = RequestMethod.POST) @RequestMapping(value = "/excel",method = RequestMethod.POST)
public ResultObj AddPeopleByexcel(@RequestParam("file") MultipartFile file) throws IOException, ParseException { public ResultObj AddPeopleByExcel() throws IOException {
Workbook workbook = WorkbookFactory.create(file.getInputStream()); HashMap hashMap = new HashMap();
// 获得工作表个数 XSSFWorkbook xssfWorkbook = new XSSFWorkbook("C:\\Users\\admin\\Desktop\\浙江泰源科技有限公司资料整理\\泰源科技人员信息.xlsx");
int sheetCount = workbook.getNumberOfSheets(); XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
// 遍历工作表 for (int i = 0; i < sheetAt.getLastRowNum(); i++) {
for (int i = 0; i < sheetCount; i++) XSSFRow row = sheetAt.getRow(i);
{ XSSFCell cellName = row.getCell(0);
Sheet sheet = workbook.getSheetAt(i); XSSFCell celPhone = row.getCell(2);
// 获得行数 hashMap.put(cellName.getStringCellValue(),celPhone.getStringCellValue());
int rows = sheet.getLastRowNum() + 1; }
Calendar calendar = Calendar.getInstance(); File file = new File("G:\\front.sql");
for (int j = 1; j < rows; j++) { BufferedReader reader = null;
Row row = sheet.getRow(j); try {
String name = row.getCell(0).getStringCellValue(); reader = new BufferedReader(new FileReader(file));
String sex = row.getCell(1).getStringCellValue(); String tempStr;
String phone = row.getCell(2).getStringCellValue(); boolean flag = false;
String idCardNumber = row.getCell(3).getStringCellValue(); int i = 0;
People people = new People(); People people = new People();
people.setName(name); PeoplePost peoplePost = new PeoplePost();
people.setSex(sex); while ((tempStr = reader.readLine()) != null) {
people.setPhone(phone); if (tempStr.contains("INSERT")&&tempStr.contains("personnelManager_people_info")){
people.setIdCardNumber(idCardNumber); flag = true;
people.setEntryTime(Instant.now()); i = 0;
peopleService.addEntity(people); }
if (tempStr.contains("at")){
flag = false;
}
if (flag){
i++;
if (i>=3){
tempStr = tempStr.substring(tempStr.indexOf("=")+1);
tempStr = tempStr.replaceAll("\'","");
}
if (i==3){
people.setPeopleId(Long.valueOf(tempStr));
}
if (i==4){
people.setName(tempStr);
if (hashMap.containsKey(tempStr)){
people.setPhone(hashMap.get(tempStr).toString());
}
}
if (i==10){
people.setIdCardNumber(tempStr);
}
if (i==11){
if (!tempStr.equals("NULL")){
Post post = new Post();
post.setPostId(Long.valueOf(tempStr));
peoplePost.setPeople(people);
peoplePost.setPost(post);
}
}
if (i==13){
people.setIcon(tempStr.substring(tempStr.indexOf("/")+1));
try {
people.setEntryTime(Instant.now());
peopleService.addEntity(people);
peoplePostService.addEntity(peoplePost);
}catch (Exception e){
System.out.println("1");
}
}
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} }
} }
return new ResultObj("成功"); return new ResultObj("成功");
} }
@RequestMapping(value = "/list",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(value = "/list",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResultObj getPeoplePage(@RequestBody PeoplePageableVo peopleDto){ public ResultObj getPeoplePage(@RequestBody PeoplePageableVo peopleDto){
return new ResultObj(peopleService.getList(peopleDto),"success"); return new ResultObj(peopleService.getList(peopleDto),"success");
......
...@@ -25,7 +25,6 @@ public interface PostRepository extends JpaRepository<Post, Long>, JpaSpecificat ...@@ -25,7 +25,6 @@ public interface PostRepository extends JpaRepository<Post, Long>, JpaSpecificat
@Query("update Post o set o.deleteTag = 1 where o.organizationNode.nodeId=:nodeId or o.nodeLevel like concat('%.',:nodeId,'.%') ") @Query("update Post o set o.deleteTag = 1 where o.organizationNode.nodeId=:nodeId or o.nodeLevel like concat('%.',:nodeId,'.%') ")
void deletePostByNodeId(Long nodeId); void deletePostByNodeId(Long nodeId);
@Query(value = "select new com.example.personnelmanager.entity.vo.PostVo(p.postId,p.postName,p.postIntroduction,p.organizationNode,count(ps.people.peopleId)) from " + @Query(value = "select new com.example.personnelmanager.entity.vo.PostVo(p.postId,p.postName,p.postIntroduction,p.organizationNode,count(ps.people.peopleId)) from " +
"Post p left join PeoplePost ps on p.postId = ps.post.postId where " + "Post p left join PeoplePost ps on p.postId = ps.post.postId where " +
"p.enterprise.enterpriseId =:enterpriseId and p.deleteTag=0 and p.organizationNode.nodeId =:organizationNodeId " + "p.enterprise.enterpriseId =:enterpriseId and p.deleteTag=0 and p.organizationNode.nodeId =:organizationNodeId " +
......
...@@ -28,7 +28,6 @@ import java.util.List; ...@@ -28,7 +28,6 @@ import java.util.List;
@Table(name = "organization_node") @Table(name = "organization_node")
@ToString(exclude = {"enterprise","posts","duties","legalEntity","legalEntity"}) @ToString(exclude = {"enterprise","posts","duties","legalEntity","legalEntity"})
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
@Where(clause = "delete_tag = 0")
public class OrganizationNode { public class OrganizationNode {
@Max(value = 0,groups = {GroupSave.class} ) @Max(value = 0,groups = {GroupSave.class} )
......
...@@ -3,6 +3,7 @@ package com.example.personnelmanager.entity; ...@@ -3,6 +3,7 @@ package com.example.personnelmanager.entity;
import com.example.personnelmanager.common.validIGroup.GroupSave; import com.example.personnelmanager.common.validIGroup.GroupSave;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In; import io.swagger.models.auth.In;
import lombok.Data; import lombok.Data;
import lombok.ToString; import lombok.ToString;
...@@ -34,7 +35,6 @@ import java.util.List; ...@@ -34,7 +35,6 @@ import java.util.List;
public class People { public class People {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "people_id",columnDefinition = "bigint comment '人员编号' ") @Column(name = "people_id",columnDefinition = "bigint comment '人员编号' ")
private Long peopleId; private Long peopleId;
......
...@@ -3,6 +3,7 @@ package com.example.personnelmanager.entity; ...@@ -3,6 +3,7 @@ package com.example.personnelmanager.entity;
import com.example.personnelmanager.common.validIGroup.GroupSave; import com.example.personnelmanager.common.validIGroup.GroupSave;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicInsert;
...@@ -48,6 +49,10 @@ public class User { ...@@ -48,6 +49,10 @@ public class User {
@Column(name = "administrator",columnDefinition = "bool comment '是否超级管理员'") @Column(name = "administrator",columnDefinition = "bool comment '是否超级管理员'")
private boolean administrator; private boolean administrator;
@Column(name = "repeats_num",columnDefinition = " int(11) not null COMMENT ' 如果用户姓名在数据库内重复,当第二个重复的用户姓名,注册进系统时,该数字加1。例如:张三张三2张三3 '")
@ApiModelProperty(value = "如果用户姓名在数据库内重复,当第二个重复的用户姓名,注册进系统时,该数字加1。例如:张三张三2张三3")
private Integer repeatsNum = 0;
@Column(name = "delete_tag",columnDefinition = "int default 0 comment '删除标记(0为正常,1为被删除)'") @Column(name = "delete_tag",columnDefinition = "int default 0 comment '删除标记(0为正常,1为被删除)'")
private int deleteTag; private int deleteTag;
......
package com.example.personnelmanager.entity.commonEntity; package com.example.personnelmanager.entity.commonEntity;
import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
/** /**
...@@ -11,6 +13,8 @@ import org.springframework.data.domain.Sort; ...@@ -11,6 +13,8 @@ import org.springframework.data.domain.Sort;
* @data 2020/5/13 * @data 2020/5/13
**/ **/
@Data @Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomOrder { public class CustomOrder {
private String coulmn; private String coulmn;
......
...@@ -7,12 +7,16 @@ import com.example.personnelmanager.common.utils.HttpClientUtil; ...@@ -7,12 +7,16 @@ import com.example.personnelmanager.common.utils.HttpClientUtil;
import com.example.personnelmanager.dao.OrganizationNodeRepository; import com.example.personnelmanager.dao.OrganizationNodeRepository;
import com.example.personnelmanager.dao.PostRepository; import com.example.personnelmanager.dao.PostRepository;
import com.example.personnelmanager.entity.OrganizationNode; import com.example.personnelmanager.entity.OrganizationNode;
import com.example.personnelmanager.entity.Post;
import com.example.personnelmanager.entity.WorkExperience;
import com.example.personnelmanager.entity.vo.OrganizationNodeListVo; import com.example.personnelmanager.entity.vo.OrganizationNodeListVo;
import com.example.personnelmanager.entity.UserDetail; import com.example.personnelmanager.entity.UserDetail;
import com.example.personnelmanager.entity.vo.PostVo; import com.example.personnelmanager.entity.vo.PostVo;
import com.example.personnelmanager.service.OrganizationNodeService; import com.example.personnelmanager.service.OrganizationNodeService;
import com.example.personnelmanager.service.PostService;
import com.github.wenhao.jpa.PredicateBuilder; import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications; import com.github.wenhao.jpa.Specifications;
import javafx.geometry.Pos;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
...@@ -42,6 +46,9 @@ public class OrganizationNodeServiceImpl implements OrganizationNodeService { ...@@ -42,6 +46,9 @@ public class OrganizationNodeServiceImpl implements OrganizationNodeService {
@Autowired @Autowired
PostRepository postRepository; PostRepository postRepository;
@Autowired
PostService postService;
@Autowired @Autowired
DateCenterJsonUtil dateCenterJsonUtil; DateCenterJsonUtil dateCenterJsonUtil;
...@@ -194,7 +201,13 @@ public class OrganizationNodeServiceImpl implements OrganizationNodeService { ...@@ -194,7 +201,13 @@ public class OrganizationNodeServiceImpl implements OrganizationNodeService {
//删除节点以及所有子节点 //删除节点以及所有子节点
organizationNodeRepository.deleteorganizationNode(id); organizationNodeRepository.deleteorganizationNode(id);
//删除所有被删除节点下的岗位 //删除所有被删除节点下的岗位
postRepository.deletePostByNodeId(id); PredicateBuilder<Post> or = Specifications.or();
or.eq("organizationNode.nodeId",id);
or.like("nodeLevel","%."+id+"%");
List<Post> all = postRepository.findAll(or.build());
all.forEach(post -> {
postService.delete(post.getPostId());
});
//向数据中心修改旧的数据 //向数据中心修改旧的数据
executorService.submit(() -> { executorService.submit(() -> {
httpClientUtil.put("http://124.70.194.194:8090/opt/data", dateCenterJsonUtil.initAllOrganizationNodeJsonStr(Arrays.asList(one)), "utf-8"); httpClientUtil.put("http://124.70.194.194:8090/opt/data", dateCenterJsonUtil.initAllOrganizationNodeJsonStr(Arrays.asList(one)), "utf-8");
......
...@@ -9,10 +9,7 @@ import com.example.personnelmanager.dao.PeopleRepository; ...@@ -9,10 +9,7 @@ import com.example.personnelmanager.dao.PeopleRepository;
import com.example.personnelmanager.entity.*; import com.example.personnelmanager.entity.*;
import com.example.personnelmanager.entity.vo.PeopleVo; import com.example.personnelmanager.entity.vo.PeopleVo;
import com.example.personnelmanager.entity.vo.pageableVo.PeoplePageableVo; import com.example.personnelmanager.entity.vo.pageableVo.PeoplePageableVo;
import com.example.personnelmanager.service.AgainEntryInformationService; import com.example.personnelmanager.service.*;
import com.example.personnelmanager.service.BecomeRegularWorkerService;
import com.example.personnelmanager.service.LeaveInformationService;
import com.example.personnelmanager.service.PeopleService;
import com.github.wenhao.jpa.PredicateBuilder; import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications; import com.github.wenhao.jpa.Specifications;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
...@@ -65,10 +62,14 @@ public class PeopleServiceImpl implements PeopleService { ...@@ -65,10 +62,14 @@ public class PeopleServiceImpl implements PeopleService {
@Autowired @Autowired
ExecutorService executorService; ExecutorService executorService;
@Autowired
UserServer userServer;
@Override @Override
public People addEntity(People people) { public People addEntity(People people) {
UserDetail userDetails = AuthenticationUtils.getAuthentication(); UserDetail userDetails = AuthenticationUtils.getAuthentication();
if (peopleRepository.findByPhoneAndEnterprise(people.getPhone(),userDetails.getEnterprise().getEnterpriseId()).size()>0){ List<People> byPhoneAndEnterprise = peopleRepository.findByPhoneAndEnterprise(people.getPhone(), userDetails.getEnterprise().getEnterpriseId());
if (byPhoneAndEnterprise!=null&&byPhoneAndEnterprise.size()>0){
throw new GlobalException("手机号码与其他人员重复"); throw new GlobalException("手机号码与其他人员重复");
} }
if (people.getTrialEndTime()!=null&&people.getInternshipEndTime().compareTo(Instant.now())>0){ if (people.getTrialEndTime()!=null&&people.getInternshipEndTime().compareTo(Instant.now())>0){
...@@ -95,10 +96,20 @@ public class PeopleServiceImpl implements PeopleService { ...@@ -95,10 +96,20 @@ public class PeopleServiceImpl implements PeopleService {
} }
people.setEnterprise(userDetails.getEnterprise()); people.setEnterprise(userDetails.getEnterprise());
People save = peopleRepository.save(people); People save = peopleRepository.save(people);
//向数据中心插入新的数据 //为新的人员创建账号
executorService.submit(() -> { User user = new User();
httpClientUtil.post("http://124.70.194.194:8090/opt/data", dateCenterJsonUtil.initAllPeopleJsonStr(Arrays.asList(save)), "utf-8"); user.setUsername(people.getPhone());
}); user.setAdministrator(false);
user.setCreateDate(Instant.now());
user.setName(people.getName());
user.setPassword("qwer1234");
user.setEnterprise(people.getEnterprise());
user.setPhone(people.getPhone());
userServer.addEntity(user);
// //向数据中心插入新的数据
// executorService.submit(() -> {
// httpClientUtil.post("http://124.70.194.194:8090/opt/data", dateCenterJsonUtil.initAllPeopleJsonStr(Arrays.asList(save)), "utf-8");
// });
return save; return save;
} }
......
...@@ -81,6 +81,8 @@ public class PostServiceImpl implements PostService { ...@@ -81,6 +81,8 @@ public class PostServiceImpl implements PostService {
return null; return null;
} }
@Override @Override
public Post update(Post post) { public Post update(Post post) {
Post after = postRepository.save(post); Post after = postRepository.save(post);
......
package com.example.personnelmanager.service.impl; package com.example.personnelmanager.service.impl;
import com.example.personnelmanager.entity.Enterprise;
import com.example.personnelmanager.entity.User;
import com.example.personnelmanager.entity.UserDetail; import com.example.personnelmanager.entity.UserDetail;
import com.example.personnelmanager.service.UserServer; import com.example.personnelmanager.service.UserServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.Instant;
/** /**
* 自定义用户详情Service * 自定义用户详情Service
* @author HuangXiahao * @author HuangXiahao
...@@ -17,17 +24,46 @@ import org.springframework.stereotype.Service; ...@@ -17,17 +24,46 @@ import org.springframework.stereotype.Service;
* @data 2020/5/20 * @data 2020/5/20
**/ **/
@Service @Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService { public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired @Autowired
UserServer userServer; UserServer userServer;
@Autowired
PasswordEncoder passwordEncoder;
@Override @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//如果用户存在数据库中,则直接返回用户
//如果用户不存在数据库中则为用户新建一个用户,并返回
UserDetail userDetail = userServer.selectByUserName(username); UserDetail userDetail = userServer.selectByUserName(username);
if (userDetail==null){ if (userDetail==null){
throw new UsernameNotFoundException("用户名或者密码错误"); throw new UsernameNotFoundException("用户名或者密码错误");
} }
return userDetail; return userDetail;
} }
public UserDetails loadUserByUsername(String username,String phone) throws UsernameNotFoundException {
//如果用户存在数据库中,则直接返回用户
//如果用户不存在数据库中则为用户新建一个用户,并返回
UserDetail userDetail = userServer.selectByUserName(username);
if (userDetail==null){
User user = new User();
user.setUsername(username);
user.setCreateDate(Instant.now());
Enterprise enterprise = new Enterprise();
enterprise.setEnterpriseId(1L);
user.setEnterprise(enterprise);
user.setName(username);
user.setPassword(passwordEncoder.encode("qwer1234"));
user.setPhone(phone);
log.info("用户为:"+user);
User user1 = userServer.addEntity(user);
userDetail = new UserDetail();
BeanUtils.copyProperties(user1,userDetail);
return userDetail;
}
return userDetail;
}
} }
...@@ -19,6 +19,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; ...@@ -19,6 +19,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.time.Instant;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
...@@ -41,6 +42,7 @@ public class UserServerImpl implements UserServer { ...@@ -41,6 +42,7 @@ public class UserServerImpl implements UserServer {
@Override @Override
public User addEntity(User user) { public User addEntity(User user) {
user.setPassword(passwordEncoder.encode(user.getPassword())); user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setCreateDate(Instant.now());
User addUser = userRepository.save(user); User addUser = userRepository.save(user);
return addUser; return addUser;
} }
......
...@@ -8,51 +8,52 @@ file: ...@@ -8,51 +8,52 @@ file:
otherDir: G:/other/ otherDir: G:/other/
jwtFilePath: G:/other/rsa jwtFilePath: G:/other/rsa
center:
ip: 124.70.194.194
serve: http://124.70.194.194:12346
#Eureka设置
eureka:
instance:
#服务过期时间配置,超过这个时间没有接收到心跳EurekaServer就会将这个实例剔除
#注意,EurekaServer一定要设置eureka.server.eviction-interval-timer-in-ms否则这个配置无效,默认90s
lease-expiration-duration-in-seconds: 15
lease-renewal-interval-in-seconds: 5 #服务刷新时间配置,每隔这个时间会主动心跳一次,默认30s
instance-id: ${spring.application.name}:${server.port}
prefer-ip-address: true # 是否显示ip前缀
client:
registry-fetch-interval-seconds: 5 #eureka client刷新本地缓存时间,默认30s
serviceUrl:
defaultZone: http://${center.ip}:10087/eureka/
# 监控页面配置
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
#ribbon负载均衡
ribbon:
ConnectTimeout: 250 # 连接超时时间(ms)
ReadTimeout: 2000 # 通信超时时间(ms)
OkToRetryOnAllOperations: true # 是否对所有操作重试
MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数
MaxAutoRetries: 1 # 同一实例的重试次数
ServerListRefreshInterval: 5000 #eureka客户端ribbon刷新时间,默认30s
hystrix: #center:
command: # ip: 124.70.194.194
default: # serve: http://124.70.194.194:12346
execution: ##Eureka设置
isolation: #eureka:
thread: # instance:
timeoutInMilliseconds: 20000 # #服务过期时间配置,超过这个时间没有接收到心跳EurekaServer就会将这个实例剔除
feign: # #注意,EurekaServer一定要设置eureka.server.eviction-interval-timer-in-ms否则这个配置无效,默认90s
hystrix: # lease-expiration-duration-in-seconds: 15
enabled: true # lease-renewal-interval-in-seconds: 5 #服务刷新时间配置,每隔这个时间会主动心跳一次,默认30s
# instance-id: ${spring.application.name}:${server.port}
# prefer-ip-address: true # 是否显示ip前缀
# client:
# registry-fetch-interval-seconds: 5 #eureka client刷新本地缓存时间,默认30s
# serviceUrl:
# defaultZone: http://${center.ip}:10087/eureka/
## 监控页面配置
#management:
# endpoints:
# web:
# exposure:
# include: '*'
# endpoint:
# health:
# show-details: always
##ribbon负载均衡
#ribbon:
# ConnectTimeout: 250 # 连接超时时间(ms)
# ReadTimeout: 2000 # 通信超时时间(ms)
# OkToRetryOnAllOperations: true # 是否对所有操作重试
# MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数
# MaxAutoRetries: 1 # 同一实例的重试次数
# ServerListRefreshInterval: 5000 #eureka客户端ribbon刷新时间,默认30s
#
#
#hystrix:
# command:
# default:
# execution:
# isolation:
# thread:
# timeoutInMilliseconds: 20000
#feign:
# hystrix:
# enabled: true
# 日志文件相关配置 # 日志文件相关配置
# level: {com.zity: trance } # level: {com.zity: trance }
#showSql #showSql
...@@ -62,4 +63,13 @@ logging: ...@@ -62,4 +63,13 @@ logging:
# 指定包名与日志级别 # 指定包名与日志级别
com.zjty: debug com.zjty: debug
# dao: debug spring:
\ No newline at end of file datasource:
username: root
password: Huang123+
url: jdbc:mysql://47.106.142.73:3306/PersonnelManager?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
# dao: debug
center:
ip: 124.70.194.194
serve: http://124.70.194.194:11324
\ No newline at end of file
...@@ -4,64 +4,70 @@ ...@@ -4,64 +4,70 @@
# 文件存储路径 # 文件存储路径
file: file:
imagePath: /opt/jar/workbench/personnel/image/ imagePath: /opt/jar/personnelManager/image/
otherDir: /opt/jar/workbench/personnel/other/
jwtFilePath: /opt/jar/workbench/personnel/other/rsa
server:
serverAddress: 124.70.194.194:${server.port}
#server:
# serverAddress: 124.70.194.194:${server.port}
#
center: center:
ip: 124.70.194.194 ip: 124.70.194.194
serve: http://124.70.194.194:12346 serve: http://124.70.194.194:11324
#Eureka设置 ##Eureka设置
eureka: #eureka:
instance: # instance:
#服务过期时间配置,超过这个时间没有接收到心跳EurekaServer就会将这个实例剔除 # #服务过期时间配置,超过这个时间没有接收到心跳EurekaServer就会将这个实例剔除
#注意,EurekaServer一定要设置eureka.server.eviction-interval-timer-in-ms否则这个配置无效,默认90s # #注意,EurekaServer一定要设置eureka.server.eviction-interval-timer-in-ms否则这个配置无效,默认90s
lease-expiration-duration-in-seconds: 15 # lease-expiration-duration-in-seconds: 15
lease-renewal-interval-in-seconds: 5 #服务刷新时间配置,每隔这个时间会主动心跳一次,默认30s # lease-renewal-interval-in-seconds: 5 #服务刷新时间配置,每隔这个时间会主动心跳一次,默认30s
instance-id: ${spring.application.name}:${server.port} # instance-id: ${spring.application.name}:${server.port}
prefer-ip-address: true # 是否显示ip前缀 # prefer-ip-address: true # 是否显示ip前缀
client: # client:
registry-fetch-interval-seconds: 5 #eureka client刷新本地缓存时间,默认30s # registry-fetch-interval-seconds: 5 #eureka client刷新本地缓存时间,默认30s
serviceUrl: # serviceUrl:
defaultZone: http://${center.ip}:10087/eureka/ # defaultZone: http://${center.ip}:10087/eureka/
# 监控页面配置 ## 监控页面配置
management: #management:
endpoints: # endpoints:
web: # web:
exposure: # exposure:
include: '*' # include: '*'
endpoint: # endpoint:
health: # health:
show-details: always # show-details: always
#ribbon负载均衡 ##ribbon负载均衡
ribbon: #ribbon:
ConnectTimeout: 250 # 连接超时时间(ms) # ConnectTimeout: 250 # 连接超时时间(ms)
ReadTimeout: 2000 # 通信超时时间(ms) # ReadTimeout: 2000 # 通信超时时间(ms)
OkToRetryOnAllOperations: true # 是否对所有操作重试 # OkToRetryOnAllOperations: true # 是否对所有操作重试
MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数 # MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数
MaxAutoRetries: 1 # 同一实例的重试次数 # MaxAutoRetries: 1 # 同一实例的重试次数
ServerListRefreshInterval: 5000 #eureka客户端ribbon刷新时间,默认30s # ServerListRefreshInterval: 5000 #eureka客户端ribbon刷新时间,默认30s
#
#
#hystrix:
# command:
# default:
# execution:
# isolation:
# thread:
# timeoutInMilliseconds: 20000
#feign:
# hystrix:
# enabled: true
## 日志文件相关配置
## level: {com.zity: trance }
##showSql
#logging:
# file: ./log/workbench.log
# level:
# # 指定包名与日志级别
# com.zjty: debug
# dao: debug
hystrix: spring:
command: datasource:
default: username: hxh
execution: password: Qwert123123
isolation: url: jdbc:mysql://124.70.145.101:3306/personnelManager?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
thread:
timeoutInMilliseconds: 20000
feign:
hystrix:
enabled: true
# 日志文件相关配置
# level: {com.zity: trance }
#showSql
logging:
file: ./log/workbench.log
level:
# 指定包名与日志级别
com.zjty: debug
# dao: debug # dao: debug
\ No newline at end of file
server: server:
port: 13245 port: 13245
spring: spring:
# 服务名 # 服务名
application: application:
name: 人员管理系统 name: 人员管理系统
profiles: profiles:
active: prod active: dev
datasource: datasource:
url: jdbc:mysql://124.70.194.194:3306/PersonnelManager?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8 # url: jdbc:mysql://124.70.194.194:3306/PersonnelManager?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
# url: jdbc:mysql://124.70.194.194:3306/personnelManagerTest?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8 # url: jdbc:mysql://124.70.194.194:3306/personnelManagerTest?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
password: root # password: root
username: canal # username: canal
driver-class-name: com.mysql.jdbc.Driver driver-class-name: com.mysql.jdbc.Driver
hikari: hikari:
auto-commit: false auto-commit: false
...@@ -28,5 +28,4 @@ spring: ...@@ -28,5 +28,4 @@ spring:
sql-dialect: MySQL5Dialect sql-dialect: MySQL5Dialect
jackson: jackson:
date-format: yyyy-MM-dd HH:mm:ss date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8 time-zone: GMT+8
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论