Commit fcbe0ba3 authored by 张俊's avatar 张俊

优化日志输出

parent 41eb2865
......@@ -4,6 +4,8 @@ package net.cdkj.gjj.adapter.controller;
import com.alibaba.fastjson.JSONObject;
import net.cdkj.gjj.adapter.domain.Json;
import net.cdkj.gjj.adapter.domain.TimeExpiredPoolCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
......@@ -15,45 +17,50 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping(value = "Cache")
public class CacheDemoController {
private static final Logger logger = LoggerFactory.getLogger(CacheDemoController.class);
/**
* 将从第三方拿到的token值存入java内存中,并设置对应的过期时间
*
* @return
*/
@RequestMapping(value = "/saveToken", method = RequestMethod.GET)
public static String saveToken() {
try {
//1.调用鉴权认证接口获取token值和过期时间的json字符串
// 1.调用鉴权认证接口获取token值和过期时间的json字符串
String str = TokenAcquisitionController.TokenAcquisition();
Json jsonentity = JSONObject.parseObject(str, Json.class);
if(jsonentity!=null){
if(jsonentity.isResult()){
boolean result=jsonentity.isResult();
String access_token=jsonentity.getAccess_token();
Long expires_in=jsonentity.getExpires_in();
System.out.println("result:"+result+","+"token值:"+access_token+","+"有效时间:"+expires_in);
TimeExpiredPoolCache.getInstance().put("access_token",access_token, expires_in*1000L);
if (jsonentity != null) {
if (jsonentity.isResult()) {
boolean result = jsonentity.isResult();
String access_token = jsonentity.getAccess_token();
Long expires_in = jsonentity.getExpires_in();
logger.info("result:" + result + "," + "token值:" + access_token + "," + "有效时间:" + expires_in);
TimeExpiredPoolCache.getInstance().put("access_token", access_token, expires_in * 1000L);
}
}
return "保存token进入缓冲成功";
} catch(Exception e){
return "保存token进入缓存失败";
}
return "保存token进入缓冲成功";
} catch (Exception e) {
return "保存token进入缓存失败";
}
}
/**
* 获取存入java内存中的token值
*
* @return
*/
@RequestMapping(value = "/getToken", method = RequestMethod.GET)
public static String getToken(){
public static String getToken() {
try {
String token = TimeExpiredPoolCache.getInstance().get("access_token");
if (null!=token){
String token = TimeExpiredPoolCache.getInstance().get("access_token");
if (null != token) {
return token;
}
} catch (Exception e) {
e.printStackTrace();
logger.error("{}", e);
}
return null;
}
......
......@@ -5,6 +5,8 @@ import com.alibaba.fastjson.JSONObject;
import net.cdkj.gjj.adapter.domain.HttpUtil;
import net.cdkj.gjj.adapter.domain.PropertyUtil;
import net.cdkj.gjj.adapter.domain.UnitAccountOpeningInformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
......@@ -14,7 +16,6 @@ import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import static net.cdkj.gjj.adapter.domain.GzipUtil.unzipString;
import static net.cdkj.gjj.adapter.domain.GzipUtil.zipString;
......@@ -28,7 +29,7 @@ public class ProvidentFundServicesController {
// log4j 日志实现
private static final Logger logger = Logger.getLogger(ProvidentFundServicesController.class.toString());
private static final Logger logger = LoggerFactory.getLogger(ProvidentFundServicesController.class);
/**
* 拉取单位开户数据接口
......@@ -42,7 +43,6 @@ public class ProvidentFundServicesController {
// 调用获取token的方法
String token = huoqutoken();
String provifunserviurl = PropertyUtil.getPropValue(prop, "provifunserviurl") + token;
System.out.println(provifunserviurl);
logger.info("单位开户拉取url:" + provifunserviurl);
// 发起 post 请求,并对出参进行解压缩
return HttpUtil.sendPost(provifunserviurl, data);
......@@ -143,9 +143,9 @@ public class ProvidentFundServicesController {
public String ProvidentFundServices2(HttpServletRequest request) {
// 获取请求入参
String str1 = HttpUtil.getReqData(request);
System.out.println("第三方接收的公积金服务接口参数解压之前" + str1);
logger.info("第三方接收的公积金服务接口参数解压之前" + str1);
String str2 = unzipString(str1);// 解压缩
System.out.println("第三方接收的公积金服务接口参数解压之后" + str2);
logger.info("第三方接收的公积金服务接口参数解压之后" + str2);
//-----------------------------------------------------
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", 0);
......
......@@ -4,6 +4,8 @@ package net.cdkj.gjj.adapter.controller;
import com.alibaba.fastjson.JSONObject;
import net.cdkj.gjj.adapter.domain.HttpUtil;
import net.cdkj.gjj.adapter.domain.PropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
......@@ -22,6 +24,9 @@ import static net.cdkj.gjj.adapter.domain.GzipUtil.zipString;
@RequestMapping(value = "FrontEndProcessor")
public class TokenAcquisitionController {
private static final Logger logger = LoggerFactory.getLogger(TokenAcquisitionController.class);
/**
* 测试静态方法读取配置文件属性值方法
*/
......@@ -29,7 +34,7 @@ public class TokenAcquisitionController {
@PostMapping("test")
public static void test() {
Properties prop = PropertyUtil.getConfig("application.properties");
System.out.println(PropertyUtil.getPropValue(prop, "tokenurl"));
logger.info(PropertyUtil.getPropValue(prop, "tokenurl"));
}
/**
......@@ -48,7 +53,7 @@ public class TokenAcquisitionController {
jsonObject.put("grant_type", "ip");
jsonObject.put("userid", "gjj");
String str = jsonObject.toString();
System.out.println("鉴权参数zip压缩处理之前要发送给第三方的报文:" + str);
logger.info("鉴权参数zip压缩处理之前要发送给第三方的报文:" + str);
String tokenurl = PropertyUtil.getPropValue(prop, "tokenurl");
return HttpUtil.sendPost(tokenurl, str);
}
......@@ -87,10 +92,10 @@ public class TokenAcquisitionController {
jsonObject.put("grant_type", "192.168.101.34");
jsonObject.put("userid", "gjj");
String str = jsonObject.toString();
System.out.println("未经过压缩处理的json字符串:" + str);
logger.info("未经过压缩处理的json字符串:" + str);
String s = zipString(str);// 进行zip压缩
System.out.println("压缩处理之后的json字符串:" + s);
logger.info("压缩处理之后的json字符串:" + s);
String s1 = unzipString(s);// 进行zip解压缩
System.out.println("解压缩处理之后的json字符串:" + s1);
logger.info("解压缩处理之后的json字符串:" + s1);
}
}
package net.cdkj.gjj.adapter.domain;
import net.cdkj.gjj.adapter.controller.CacheDemoController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.io.ByteArrayOutputStream;
......@@ -12,8 +15,13 @@ import java.util.zip.Inflater;
* json字符串zip压缩,解压缩工具类
*/
public class GzipUtil {
private static final Logger logger = LoggerFactory.getLogger(CacheDemoController.class);
/**
* 压缩
*
* @param unzip
* @return
*/
......@@ -23,6 +31,7 @@ public class GzipUtil {
/**
* 对cpspJson进行解压
*
* @param zip
* @return
*/
......@@ -30,13 +39,13 @@ public class GzipUtil {
try {
byte[] decode = new sun.misc.BASE64Decoder().decodeBuffer(zip);
String unziqStr = unzipByte(decode);
//如果解压缩失败,返回原数据
if (StringUtils.isEmpty(unziqStr)){
// 如果解压缩失败,返回原数据
if (StringUtils.isEmpty(unziqStr)) {
return zip;
}
return unziqStr;
} catch (IOException ex) {
System.out.println("解压文件失败"+ex);
logger.error("解压文件失败" + ex);
return zip;
}
}
......@@ -47,12 +56,14 @@ public class GzipUtil {
byte[] decode = new sun.misc.BASE64Decoder().decodeBuffer(zip);
return unzipByte(decode);
} catch (IOException ex) {
System.out.println("解压文件失败"+ex);
logger.error("解压文件失败" + ex);
return null;
}
}
/**
* 压缩
*
* @param unzip
* @return
*/
......@@ -87,7 +98,7 @@ public class GzipUtil {
outputStream.write(bytes, 0, length);
}
} catch (DataFormatException e) {
System.out.println("解压缩失败"+e);
logger.error("解压缩失败" + e);
return null;
} finally {
inflater.end();
......
package net.cdkj.gjj.adapter.domain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
......@@ -9,6 +12,7 @@ import java.util.zip.GZIPInputStream;
public class HttpUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
/**
* 获取请求入参数据
......@@ -22,10 +26,10 @@ public class HttpUtil {
json.append(line);
}
} catch (Exception e) {
System.out.println(e);
logger.error("{}", e);
}
String str = json.toString();
System.out.println("要发送给第三方的公积金系统服务报文:" + str);
logger.info("要发送给第三方的公积金系统服务报文:" + str);
return str;
}
......@@ -78,14 +82,13 @@ public class HttpUtil {
while ((temp = br.readLine()) != null) {
sb.append(temp);
}
System.out.println("第三方返回的zip解压缩之后的报文:" + sb);
logger.info("第三方返回的zip解压缩之后的报文:" + sb);
return sb.toString();
} else {
System.out.println("请求失败!!!");
logger.info("请求失败!!!");
}
} catch (
IOException e) {
e.printStackTrace();
} catch (IOException e) {
logger.error("{}", e);
} finally {
if (out != null) {
try {
......
......@@ -13,11 +13,11 @@ public class Json {
//
// private String grant_type;
private String access_token;
private String access_token;
private Long expires_in;
private Long expires_in;
private boolean result;
private boolean result;
public String getAccess_token() {
return access_token;
......
package net.cdkj.gjj.adapter.domain;
import net.cdkj.gjj.adapter.controller.CacheDemoController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
......@@ -8,43 +13,48 @@ import java.util.Properties;
* 获取配置文件application.properties里的属性值所用到的工具类
*/
public class PropertyUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
/**
* 读取 classpath 下 指定的properties配置文件,加载到Properties并返回Properties
*
* @param name 配置文件名,如:mongo.properties
* @return
*/
public static Properties getConfig(String name){
Properties props=null;
try{
public static Properties getConfig(String name) {
Properties props = null;
try {
props = new Properties();
InputStream in = PropertyUtil.class.getClassLoader().getResourceAsStream(name);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
props.load(bf);
in.close();
}catch(Exception ex){
ex.printStackTrace();
} catch (Exception e) {
logger.error("{}", e);
}
return props;
}
public static String getPropValue(Properties prop,String key){
if(key == null || "".equals(key.trim())){
public static String getPropValue(Properties prop, String key) {
if (key == null || "".equals(key.trim())) {
return null;
}
String value = prop.getProperty(key);
if(value == null){
if (value == null) {
return null;
}
value = value.trim();
//判断是否是环境变量配置属性,例如 server.env=${serverEnv:local}
if(value.startsWith("${") && value.endsWith("}") && value.contains(":")){
// 判断是否是环境变量配置属性,例如 server.env=${serverEnv:local}
if (value.startsWith("${") && value.endsWith("}") && value.contains(":")) {
int indexOfColon = value.indexOf(":");
String envName = value.substring(2,indexOfColon);
//获取系统环境变量 envName 的内容,如果没有找到,则返回defaultValue
String envName = value.substring(2, indexOfColon);
// 获取系统环境变量 envName 的内容,如果没有找到,则返回defaultValue
String envValue = System.getenv(envName);
if(envValue == null){
//配置的默认值
return value.substring(indexOfColon+1,value.length()-1);
if (envValue == null) {
// 配置的默认值
return value.substring(indexOfColon + 1, value.length() - 1);
}
return envValue;
}
......
......@@ -11,8 +11,8 @@ import java.util.concurrent.ConcurrentHashMap;
* Cache缓存类
*/
public class TimeExpiredPoolCache {
private static long defaultCachedMillis = 30 * 1000L;//过期时间默认10秒
private static long timerMillis = 30 * 1000L;//定时清理默认10秒
private static long defaultCachedMillis = 30 * 1000L;// 过期时间默认10秒
private static long timerMillis = 30 * 1000L;// 定时清理默认10秒
/**
* 对象池
*/
......@@ -21,25 +21,30 @@ public class TimeExpiredPoolCache {
* 对象单例
*/
private static TimeExpiredPoolCache instance = null;
private TimeExpiredPoolCache() {
dataPool = new ConcurrentHashMap<String, DataWrapper<?>>();
}
private static synchronized void syncInit() {
if (instance == null) {
instance = new TimeExpiredPoolCache();
initTimer();
}
}
public static TimeExpiredPoolCache getInstance() {
if (instance == null) {
syncInit();
}
return instance;
}
/**
* 定时器定时清理过期缓存
*/
private static Timer timer = new Timer();
private static void initTimer() {
timer.scheduleAtFixedRate(new TimerTask() {
@Override
......@@ -47,7 +52,7 @@ public class TimeExpiredPoolCache {
try {
clearExpiredCaches();
} catch (Exception e) {
//logger.error("clearExpiredCaches error.", e);
// logger.error("clearExpiredCaches error.", e);
}
}
}, timerMillis, timerMillis);
......@@ -55,24 +60,25 @@ public class TimeExpiredPoolCache {
/**
* 缓存数据
* @param key key值
* @param data 缓存数据
*
* @param key key值
* @param data 缓存数据
* @param cachedMillis 过期时间
* @param dataRenewer 刷新数据
* @param dataRenewer 刷新数据
* @return
*/
@SuppressWarnings("unchecked")
public <T> T put(String key, T data, long cachedMillis, DataRenewer<T> dataRenewer) throws Exception {
DataWrapper<T> dataWrapper = (DataWrapper<T>)dataPool.get(key);
DataWrapper<T> dataWrapper = (DataWrapper<T>) dataPool.get(key);
if (data == null && dataRenewer != null) {
data = dataRenewer.renewData();
}
//当重新获取数据为空,直接返回不做put
if (data == null){
// 当重新获取数据为空,直接返回不做put
if (data == null) {
return null;
}
if (dataWrapper != null) {
//更新
// 更新
dataWrapper.update(data, cachedMillis);
} else {
dataWrapper = new DataWrapper<T>(data, cachedMillis);
......@@ -80,18 +86,20 @@ public class TimeExpiredPoolCache {
}
return data;
}
/**
* 直接设置缓存值和时间
*
* @param key
* @param data
* @param cachedMillis
* @return
*/
@SuppressWarnings("unchecked")
public <T> T put(String key, T data, long cachedMillis) throws Exception{
DataWrapper<T> dataWrapper = (DataWrapper<T>)dataPool.get(key);
public <T> T put(String key, T data, long cachedMillis) throws Exception {
DataWrapper<T> dataWrapper = (DataWrapper<T>) dataPool.get(key);
if (dataWrapper != null) {
//更新
// 更新
dataWrapper.update(data, cachedMillis);
} else {
dataWrapper = new DataWrapper<T>(data, cachedMillis);
......@@ -99,8 +107,10 @@ public class TimeExpiredPoolCache {
}
return data;
}
/**
* 默认构造时间的缓存数据
*
* @param key
* @param data
* @param dataRenewer
......@@ -110,8 +120,10 @@ public class TimeExpiredPoolCache {
public <T> T put(String key, T data, DataRenewer<T> dataRenewer) throws Exception {
return put(key, data, defaultCachedMillis, dataRenewer);
}
/**
* 获取缓存
*
* @param key
* @param cachedMillis
* @param dataRenewer
......@@ -119,20 +131,22 @@ public class TimeExpiredPoolCache {
*/
@SuppressWarnings("unchecked")
public <T> T get(String key, long cachedMillis, DataRenewer<T> dataRenewer) throws Exception {
DataWrapper<T> dataWrapper = (DataWrapper<T>)dataPool.get(key);
DataWrapper<T> dataWrapper = (DataWrapper<T>) dataPool.get(key);
if (dataWrapper != null && !dataWrapper.isExpired()) {
return dataWrapper.data;
}
return put(key, null, cachedMillis, dataRenewer);
}
@SuppressWarnings("unchecked")
public <T> T get(String key) throws Exception {
DataWrapper<T> dataWrapper = (DataWrapper<T>)dataPool.get(key);
DataWrapper<T> dataWrapper = (DataWrapper<T>) dataPool.get(key);
if (dataWrapper != null && !dataWrapper.isExpired()) {
return dataWrapper.data;
}
return null;
}
/**
* 清除缓存
*/
......@@ -142,8 +156,8 @@ public class TimeExpiredPoolCache {
/**
* 删除指定key的value
* */
public void remove(String key){
*/
public void remove(String key) {
dataPool.remove(key);
}
......@@ -163,19 +177,24 @@ public class TimeExpiredPoolCache {
* 缓存时间
*/
private long cachedMillis;
private DataWrapper(T data, long cachedMillis) {
this.update(data, cachedMillis);
}
public void update(T data, long cachedMillis) {
this.data = data;
this.cachedMillis = cachedMillis;
this.updateExpiredTime();
}
public void updateExpiredTime() {
this.expiredTime = System.currentTimeMillis() + cachedMillis;
}
/**
* 数据是否过期
*
* @return
*/
public boolean isExpired() {
......@@ -185,6 +204,7 @@ public class TimeExpiredPoolCache {
return true;
}
}
/**
* 数据构造
*/
......@@ -198,7 +218,7 @@ public class TimeExpiredPoolCache {
private static void clearExpiredCaches() {
List<String> expiredKeyList = new LinkedList<String>();
for(Entry<String, DataWrapper<?>> entry : dataPool.entrySet()){
for (Entry<String, DataWrapper<?>> entry : dataPool.entrySet()) {
if (entry.getValue().isExpired()) {
expiredKeyList.add(entry.getKey());
}
......
......@@ -10,53 +10,53 @@ import java.util.Date;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UnitAccountOpeningInformation {
private String ywbh;
private String ywbh;
private String busId;
private String busId;
private String uscc;
private String uscc;
private String entName;
private String entName;
private String dom;
private String dom;
private Date estDate;
private String lerep;
private String lerep;
private String cerType;
private String cerType;
private String cerNo;
private String cerNo;
private String operatorName;
private String operatorName;
private String operatorCerNo;
private String operatorCerNo;
private String operatorPhone;
private String operatorPhone;
private String oplocdistrict;
private String oplocdistrict;
private String unitNature;
private String unitNature;
private String economicType;
private String economicType;
private String industryphy;
private String industryphy;
private String unitPayDay;
private String unitPayDay;
private String unitDepPro;
private String unitDepPro;
private String personalDepPro;
private String personalDepPro;
private String zxdqbm;
private String zxdqbm;
private String lcls;
private String lcls;
private String dwzh;
private String dwzh;
private String errcode;
private String errcode;
private String errmsg;
private String errmsg;
public String getBusId() {
......
......@@ -21,3 +21,5 @@ dwxhPullUrl:http://59.208.149.225:18080/sjzt/api/dx/e39a08e0a52b413897f9d2335954
#单位销户推送url
dwxhPushUrl:http://59.208.149.225:18080/sjzt/api/retGjjProgData?access_token=
# 日志配置
logging.config:classpath:logback.xml
\ No newline at end of file
......@@ -18,21 +18,13 @@
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>
<fileNamePattern>${log.path}.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
......@@ -40,9 +32,9 @@
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>
<fileNamePattern>${log.path}-error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
......@@ -57,38 +49,13 @@
</filter>
</appender>
<!-- 用户访问日志输出 -->
<appender name="sys-user" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-user.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天回滚 daily -->
<fileNamePattern>${log.path}/sys-user.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统模块日志级别控制 -->
<logger name="com.ruoyi" level="info"/>
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="warn"/>
<!-- 控制台输出 -->
<root level="info">
<appender-ref ref="console"/>
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="console"/>
<appender-ref ref="file_info"/>
<appender-ref ref="file_error"/>
</root>
<!-- 系统模块日志级别控制 -->
<logger name="net.cdkj" level="debug"/>
<!--系统用户操作日志-->
<logger name="sys-user" level="info">
<appender-ref ref="sys-user"/>
</logger>
</configuration>
\ No newline at end of file
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