Forráskód Böngészése

增加了配置中心,用于保存公共的配置。

yangzhijie 5 éve
szülő
commit
169eaafed1

+ 17 - 0
pom.xml

@@ -54,6 +54,23 @@
 			<artifactId>spring-cloud-starter-gateway</artifactId>
 		</dependency>
 
+		<!--sleuth日志跟踪-->
+		<dependency>
+		    <groupId>org.springframework.cloud</groupId>
+		    <artifactId>spring-cloud-starter-sleuth</artifactId>
+		</dependency>
+		
+		<!-- spring cloud config 客户端包 -->
+		<dependency>
+		    <groupId>org.springframework.cloud</groupId>
+		    <artifactId>spring-cloud-starter-config</artifactId>
+		</dependency>
+		
+		<dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-actuator</artifactId>
+        </dependency>
+        
 		<dependency>
 			<groupId>org.springframework.boot</groupId>
 			<artifactId>spring-boot-starter-test</artifactId>

+ 4 - 2
src/main/java/com/leanwo/gateway/GatewayApp.java

@@ -6,8 +6,10 @@ import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
 import org.springframework.cloud.openfeign.EnableFeignClients;
+import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ImportResource;
 
+import com.fasterxml.jackson.databind.ObjectMapper;
 import com.leanwo.gateway.util.ProgramStopUtil;
 
 @EnableFeignClients // 启动Feign客户端
@@ -22,9 +24,9 @@ public class GatewayApp {
 		
 		SpringApplication.run(GatewayApp.class, args);
 
-		logger.info("网关服务器启动成功。");
-		
 		ProgramStopUtil.generateStopBat();
 
+		logger.info("网关服务器启动成功。");
 	}
+	
 }

+ 16 - 0
src/main/java/com/leanwo/gateway/config/BeanFactory.java

@@ -0,0 +1,16 @@
+package com.leanwo.gateway.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Configuration
+public class BeanFactory {
+
+	@Bean("objectMapper1")
+	public ObjectMapper objectMapper() {
+		ObjectMapper objectMapper = new ObjectMapper();
+		return objectMapper;
+	}
+}

+ 42 - 0
src/main/java/com/leanwo/gateway/config/CloudConfig.java

@@ -0,0 +1,42 @@
+package com.leanwo.gateway.config;
+
+import javax.annotation.PostConstruct;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.cloud.context.config.annotation.RefreshScope;
+import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
+import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.event.EventListener;
+
+/**
+ * 公共配置.
+ */
+@Configuration
+@RefreshScope
+public class CloudConfig {
+
+    /**  账套信息. */
+    @Value("${accountManagement}")
+    private String accountManagement;
+
+
+    
+    /**
+     * Gets the 账套信息.
+     *
+     * @return the 账套信息
+     */
+    public String getAccountManagement() {
+        return accountManagement;
+    }
+
+    /**
+     * Sets the 账套信息.
+     *
+     * @param accountManagement the new 账套信息
+     */
+    public void setAccountManagement(String accountManagement) {
+        this.accountManagement = accountManagement;
+    }
+}

+ 0 - 32
src/main/java/com/leanwo/gateway/rest/AccountManagementResource.java

@@ -1,32 +0,0 @@
-package com.leanwo.gateway.rest;
-
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.ResponseBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import com.leanwo.gateway.service.AccountManagementService;
-
-
-@RestController
-@RequestMapping("/api/AccountManagementResource")
-public class AccountManagementResource {
-
-	@Autowired
-	private AccountManagementService accountManagementService;
-	
-	/**
-	 * 重新加载账套数据并且重新加载数据源
-	 * @author GuoZhiBo 20200616
-	 * @return
-	 */
-	@RequestMapping(value = "/loadAccountManagement", method = RequestMethod.POST, produces = "application/json")
-	@ResponseBody
-	public boolean loadAccountManagement() {
-		accountManagementService.loadAccountManagement(true);
-		return true;
-	}
-}

+ 29 - 13
src/main/java/com/leanwo/gateway/service/AccountManagementServiceImpl.java

@@ -1,13 +1,21 @@
 package com.leanwo.gateway.service;
 
+import java.util.ArrayList;
 import java.util.List;
-
+import java.util.Set;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
+import org.springframework.context.event.EventListener;
 import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
 
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.leanwo.gateway.config.CloudConfig;
 import com.leanwo.gateway.dto.AccountManagementDto;
 import com.leanwo.gateway.util.LoginContext;
 import com.leanwo.gateway.util.LoginContextUtil;
@@ -17,27 +25,26 @@ public class AccountManagementServiceImpl implements AccountManagementService {
 
 	private static Logger logger = LoggerFactory.getLogger(AccountManagementServiceImpl.class);
 
+	private List<AccountManagementDto> accountManagementDtos = null;
+
 	@Autowired
-	private ProdogServer prodogServer;
+	private CloudConfig cloudConfig;
 
 	@Autowired
-	private TokenService tokenService;
+	@Qualifier("objectMapper1")
+	private ObjectMapper objectMapper;
 	
-	private List<AccountManagementDto> accountManagementDtos = null;
-
 	@Override
 	public List<AccountManagementDto> loadAccountManagement(boolean force) {
 		try {
 			if (accountManagementDtos == null || force) {
-				LoginContext loginContext = LoginContextUtil.getLoginContext();
-				if (loginContext == null) {
-					loginContext = new LoginContext();
-					loginContext.setAccountId(0L);
-					String tempToken = tokenService.generateTempToken();
-					loginContext.setToken(tempToken);
-					LoginContextUtil.setLoginContext(loginContext);
+				String accountManagement = cloudConfig.getAccountManagement();
+				if(!StringUtils.isEmpty(accountManagement)) {
+					accountManagementDtos = objectMapper.readValue(accountManagement, new TypeReference<List<AccountManagementDto>>() {});
+					if(accountManagementDtos == null) {
+						accountManagementDtos = new ArrayList<AccountManagementDto>();
+					}
 				}
-				accountManagementDtos = prodogServer.getAccountManagementDtoCache();
 			}
 		}catch(Exception ex) {
 			logger.error("从Prodog-Server服务器获取账套信息失败。", ex);
@@ -63,4 +70,13 @@ public class AccountManagementServiceImpl implements AccountManagementService {
 
 		return 0L;
 	}
+	
+
+	@EventListener(EnvironmentChangeEvent.class)
+	public void onApplicationEvent(EnvironmentChangeEvent event) {
+		Set<String> keys = event.getKeys();
+		if(keys != null && keys.contains("accountManagement")) {
+			loadAccountManagement(true);
+		}
+	}
 }

+ 0 - 33
src/main/java/com/leanwo/gateway/service/ProdogServer.java

@@ -1,33 +0,0 @@
-package com.leanwo.gateway.service;
-
-
-import java.rmi.ServerException;
-import java.util.List;
-
-import org.springframework.cloud.openfeign.FeignClient;
-import org.springframework.stereotype.Service;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-
-import com.leanwo.gateway.dto.AccountManagementDto;
-import com.leanwo.gateway.exception.KeepErrMsgConfiguration;
-
-
-/**
- * 调用应用服务器.
- * @author GuoZhiBo
- * @Date 20200616
- */
-
-@Service
-@FeignClient(value = "prodog-server", fallback = ProdogServerImpl.class, configuration = { KeepErrMsgConfiguration.class })
-public interface ProdogServer {
-	
-	/**
-	 * 获取所有账套信息
-	 * @return
-	 * @author GuoZhiBo 20200616
-	 */
-	@RequestMapping(value = "/api/AccountManagementResource/getAccountManagementDtoCache", method = RequestMethod.GET, produces = "application/json")
-	List<AccountManagementDto> getAccountManagementDtoCache();
-}

+ 0 - 30
src/main/java/com/leanwo/gateway/service/ProdogServerImpl.java

@@ -1,30 +0,0 @@
-package com.leanwo.gateway.service;
-
-import java.util.List;
-
-import org.springframework.stereotype.Component;
-
-import com.leanwo.gateway.dto.AccountManagementDto;
-import com.leanwo.gateway.exception.ServerException;
-
-
-@Component
-public class ProdogServerImpl implements ProdogServer {
-
-	private static final String ERROR_MSG = "应用服务器异常";
-
-	/**
-	 * 获取默认的异常
-	 * @return
-	 * @throws ServerException 
-	 */
-	public ServerException getDefaultException() throws ServerException {
-		throw new ServerException(ERROR_MSG);
-	}
-	
-	@Override
-	public List<AccountManagementDto> getAccountManagementDtoCache() {
-		throw getDefaultException();
-	}
-	
-}

+ 0 - 11
src/main/java/com/leanwo/gateway/service/TokenService.java

@@ -1,11 +0,0 @@
-package com.leanwo.gateway.service;
-
-public interface TokenService {
-
-	/**
-	 * 生成临时的token
-	 * @return
-	 */
-	String generateTempToken();
-
-}

+ 0 - 93
src/main/java/com/leanwo/gateway/service/TokenServiceImpl.java

@@ -1,93 +0,0 @@
-package com.leanwo.gateway.service;
-
-import java.util.Date;
-import java.util.UUID;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Configuration;
-
-import com.auth0.jwt.JWT;
-import com.auth0.jwt.algorithms.Algorithm;
-import com.auth0.jwt.exceptions.JWTCreationException;
-import com.leanwo.gateway.exception.TokenException;
-
-@Configuration
-public class TokenServiceImpl implements TokenService {
-
-	private static Logger logger = LoggerFactory.getLogger(TokenServiceImpl.class);
-	
-    /** The regist overtime ms. */
-    // 注册超时时间
-    private static long REGIST_OVERTIME_MS = (long)(30 * 1000);
-
-    /** The token secret. */
-    // 密钥
-    @Value("${server.token.secret}")
-    private String tokenSecret;
-
-    /** The token issuer. */
-    // 密钥
-    @Value("${server.token.issuer}")
-    private String tokenIssuer;
-    
-    @Override
-    public String generateTempToken() {
-        long currentMs = new Date().getTime();
-        Date expireDate = new Date(currentMs + REGIST_OVERTIME_MS);
-        Date notBeforeDate = new Date(currentMs + 3 * 1000);
-        String tokenString = null;
-        // Create and Sign a Token
-        try {
-            Algorithm algorithm = Algorithm.HMAC256(tokenSecret);
-            tokenString = JWT.create().withIssuer(tokenIssuer) // 签发者
-                .withExpiresAt(expireDate) // 过期时间
-                .withIssuedAt(new Date()) // 签发时间
-                // .withNotBefore(notBeforeDate) // 下次可访问的时间
-                .withClaim("uuid", UUID.randomUUID().toString()).sign(algorithm);
-        } catch (JWTCreationException exception) {
-            logger.error("JWT Token生成失败.", exception);
-            throw new TokenException("JWT Token生成失败.");
-        }
-        return tokenString;
-    }
-    
-
-    /**
-     * Gets the token 密钥.
-     *
-     * @return the token 密钥
-     */
-    public String getTokenSecret() {
-        return tokenSecret;
-    }
-
-    /**
-     * Sets the token 密钥.
-     *
-     * @param tokenSecret the new token 密钥
-     */
-    public void setTokenSecret(String tokenSecret) {
-        this.tokenSecret = tokenSecret;
-    }
-
-    /**
-     * Gets the token 授权单位.
-     *
-     * @return the token 授权单位
-     */
-    public String getTokenIssuer() {
-        return tokenIssuer;
-    }
-
-    /**
-     * Sets the token 授权单位.
-     *
-     * @param tokenIssuer the new token 授权单位
-     */
-    public void setTokenIssuer(String tokenIssuer) {
-        this.tokenIssuer = tokenIssuer;
-    }
-    
-}

+ 2 - 27
src/main/resources/Application.yml

@@ -16,10 +16,8 @@ server:
   compression:
     enabled: true
     mime-types: application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css,font/woff2
+    
 spring:
-  application:
-    # 应用名称,会在Eureka中作为服务的id标识(serviceId)
-    name: gateway-server
   # 修改文件上传大小的限制
   servlet:
     multipart:
@@ -37,7 +35,7 @@ spring:
         - id: application_server
           uri: lb://prodog-server
           predicates:
-            - Path=/api/**,/druid/**
+            - Path=/api/**,/druid/**,/rest-api/**
         - id: dingtalk_server
           uri: lb://dingtalk-server
           predicates:
@@ -86,26 +84,3 @@ spring:
           uri: lb://file-server
           predicates:
             - Path=/**
-          
-          
-#Eureka Server服务器地址.
-eureka:
-  instance:
-    prefer-ip-address: true
-    #Eureka客户端向服务端发送心跳的时间间隔,单位为秒(客户端告诉服务端自己会按照该规则),默认30
-    lease-renewal-interval-in-seconds: 5
-    #Eureka服务端在收到最后一次心跳之后等待的时间上限,单位为秒,超过则剔除(客户端告诉服务端按照此规则等待自己),默认90
-    lease-expiration-duration-in-seconds: 10
-  client:
-    fetch-registry: true
-    register-with-eureka: true
-    serviceUrl:
-      defaultZone: http://localhost:88/eureka/
-
-    
-      
-ribbon:
-  #请求处理的超时时间
-  ReadTimeout: 12000000
-  #请求连接的超时时间
-  ConnectTimeout: 3000000

+ 44 - 0
src/main/resources/bootstrap.yml

@@ -0,0 +1,44 @@
+spring:
+  application:
+    # 应用名称,会在Eureka中作为服务的id标识(serviceId)
+    name: gateway-server
+  cloud: 
+      config: 
+        name: common
+        # dev 开发环境配置文件 |  test 测试环境  |  pro 正式环境
+        profile: dev
+        discovery: 
+          # 启用发现服务功能
+          enabled: true
+          # 指定配置中心名称(如果使用eureka可以这样配置)
+          service-id: config-server
+        
+      
+#Eureka Server服务器地址.
+eureka:
+  instance:
+    prefer-ip-address: true
+    #Eureka客户端向服务端发送心跳的时间间隔,单位为秒(客户端告诉服务端自己会按照该规则),默认30
+    lease-renewal-interval-in-seconds: 2
+    #Eureka服务端在收到最后一次心跳之后等待的时间上限,单位为秒,超过则剔除(客户端告诉服务端按照此规则等待自己),默认90
+    lease-expiration-duration-in-seconds: 4
+  client:
+    fetch-registry: true
+    register-with-eureka: true
+    # Eureka 客户端每隔多久去 Eureka 服务器拉取最新的注册信息,默认值 30(秒)
+    registryFetchIntervalSeconds: 2
+    serviceUrl:
+      defaultZone: http://localhost:88/eureka/
+ 
+ribbon:
+  #请求处理的超时时间
+  ReadTimeout: 12000000
+  #请求连接的超时时间
+  ConnectTimeout: 3000000
+
+
+management:
+  endpoints:
+    web:
+      exposure:
+        include: refresh

+ 5 - 4
src/main/resources/log4j2.xml

@@ -11,16 +11,17 @@
             <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
             <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY"/>
             <!-- 这个都知道是输出日志的格式 -->
-            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss z} %-5level %class{36} [%L] [%M] - %msg%xEx%n"/>
+            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level [%logger{50}:%L] [%X{X-B3-TraceId},%X{X-B3-SpanId}] - %msg%n" />
+
         </Console>
         
 		<!-- 这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
 		<RollingFile name="RollingFile"
 			fileName="${LOG_HOME}/server-management.log"
 			filePattern="${LOG_HOME}/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
-			<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
-			<PatternLayout
-				pattern="%d{yyyy-MM-dd HH:mm:ss z} %-5level %class{36} [%L] [%M] - %msg%xEx%n" />
+			<ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY" />
+            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level [%logger{50}:%L] [%X{X-B3-TraceId},%X{X-B3-SpanId}] - %msg%n" />
+
 			<SizeBasedTriggeringPolicy size="2MB" />
 		</RollingFile>
 	</appenders>

+ 5 - 4
src/main/resources/run.bat

@@ -1,6 +1,7 @@
 :: 网关服务器
+:: 启动顺序1
+:: 菜单顺序2
 title Gateway Server
-set current_path="%cd%"
-cd %current_path%
-java -jar %current_path%\GatewayServer.jar
-pause
+set current_path=%~dp0
+cd /d %~dp0
+java -jar -Xms64m -Xmx128m %current_path%\GatewayServer.jar