一、使用切面來管理日誌
單個服務可以定義一個切面,在切點裏把所有的controller給包起來,所有的controller均放在web包下:
package com.hand.hcf.app.expense.logaop;
import jline.internal.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.logging.Logger;
/**
* WebLogAspect
*
* @Auther: zhengbing.zhang
* @Date:2020/6/28
* @remark
*/
@Aspect
@Component
public class WebLogAspect {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
@Pointcut("execution(public * com.hand.hcf.app.expense.*.web..*.*(..))")
public void webLog(){}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到請求,記錄請求內容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request=attributes.getRequest();
logger.info("URL:"+request.getRequestURL().toString());
logger.info("HTTP_METHOD:"+request.getMethod());
logger.info("IP :"+ request.getRemoteAddr());
logger.info("CLASS_METHOD:" +joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
logger.info("ARGS:"+Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning="ret",pointcut="webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 處理完請求,返回內容
logger.info("RESPONSE : " + ret);
}
}
可以通過此方式來記錄請求的相關信息,url,method,ip,類和方法名以及方法的參數。
打印出的日誌信息如下:
2020-06-28 10:38:22.194 INFO [fec-expense,,,] 35428 --- [ XNIO-1 task-1] c.h.hcf.app.expense.logaop.WebLogAspect : URL:http://10.72.9.128:9096/api/expense/report/line/query/by/headerId
2020-06-28 10:38:22.195 INFO [fec-expense,,,] 35428 --- [ XNIO-1 task-1] c.h.hcf.app.expense.logaop.WebLogAspect : HTTP_METHOD:GET
2020-06-28 10:38:22.195 INFO [fec-expense,,,] 35428 --- [ XNIO-1 task-1] c.h.hcf.app.expense.logaop.WebLogAspect : IP :10.72.9.128
2020-06-28 10:38:22.196 INFO [fec-expense,,,] 35428 --- [ XNIO-1 task-1] c.h.hcf.app.expense.logaop.WebLogAspect : CLASS_METHOD:com.hand.hcf.app.expense.report.web.ExpenseReportController.getExpenseReportLinesByHeaderId
2020-06-28 10:38:22.197 INFO [fec-expense,,,] 35428 --- [ XNIO-1 task-1] c.h.hcf.app.expense.logaop.WebLogAspect : ARGS:[1199962780901412865, Page request [number: 0, size 5, sort: UNSORTED]]
二、oauth2+redis+分佈式定時任務來備份所有服務的請求
實現原理:
1.在微服務架構體系中,每個服務的請求都會進行認證,可以通過 oauth2將每個服務的請求均需要定向到auth服務去鑑權。
2.使用redis將所有訪問的請求給緩存起來,避免過多請求給數據庫造成訪問壓力。
3.使用定時任務將redis服務器裏的一定時間內的所有請求給備份到數據庫中。
security.oauth2.client.access-token-uri = http://fec-api-gateway-uat.internal.aegonthtf.com/fec-auth/oauth/token
security.oauth2.client.client-authentication-scheme = form
security.oauth2.client.client-id = implement-integration
security.oauth2.client.client-secret = K2QzPPz3fqQNEnsbwupD1b1IDPPg0RfkdWalXysL7wd
security.oauth2.client.grant-type = client_credentials
security.oauth2.resource.user-info-uri =http://fec-api-gateway-uat.internal.aegonthtf.com/fec-auth/api/check_token
利用oauth2的特性,可以將 所有的訪問請求重定向到/api/check_token上去鑑權,那麼所有的請求都會在這個接口上。
oauth2的版本爲:
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</artifactId>
</dependency>
package com.hand.hcf.app.auth.web;
import com.hand.hcf.app.auth.service.UserService;
import com.hand.hcf.core.exception.core.UnauthenticatedException;
import com.hand.hcf.core.security.domain.Authority;
import com.hand.hcf.core.security.domain.PrincipalLite;
import jline.internal.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api")
public class AccountResource {
@Autowired
private UserService userService;
@GetMapping(value = "/check_token")
public PrincipalLite checkToken() {
if (SecurityContextHolder.getContext().getAuthentication() instanceof OAuth2Authentication) {
OAuth2Authentication auth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
if (auth2Authentication.getUserAuthentication() != null) {
if (auth2Authentication.getPrincipal() instanceof Map) {
Log.info("auth2Authentication is map");
}
//備份請求
userService.backRequest();
return (PrincipalLite) auth2Authentication.getPrincipal();
} else {
String clientId = auth2Authentication.getOAuth2Request().getClientId();
PrincipalLite principalLite = userService.getUserByOauthClientId(clientId);
if(null == principalLite){
principalLite = new PrincipalLite();
}
principalLite.setLogin((String) auth2Authentication.getPrincipal());
principalLite.setAuthorities(auth2Authentication.getAuthorities().stream().map(right -> new Authority(right.getAuthority())).collect(Collectors.toSet()));
userService.backRequest();
return principalLite;
}
} else {
throw new UnauthenticatedException();
}
}
}