最近看到一個有趣的開源項目pig,主要的技術點在認證受權中心,spring security oauth,zuul網關實現,Elastic-Job定時任務,趁着剛剛入門微服務,趕快寫個博客分析一下。此篇文章主要用於我的備忘。若是有不對,請批評。😭html
因爲每一個模塊篇幅較長,且部份內容和前文有重疊,乾貨和圖片較少,閱讀時使用旁邊的導航功能體驗較佳。😉前端
想要解鎖更多新姿式?請訪問https://blog.tengshe789.tech/vue
本篇文章是對基於spring boot
1.5的pig 1
版本作的分析,不是收費的pigx 2
版本。java
配置中心:gitee.com/cqzqxq_lxh/…mysql
pigx.pig4cloud.com/#/wel/indexgithub
請確保啓動順序(要先啓動認證中心,再啓動網關)web
老規矩,自上到下看代碼,先從接口層看起redis
@RestController
@RequestMapping("/authentication")
public class AuthenticationController {
@Autowired
@Qualifier("consumerTokenServices")
private ConsumerTokenServices consumerTokenServices;
/** * 認證頁面 * @return ModelAndView */
@GetMapping("/require")
public ModelAndView require() {
return new ModelAndView("ftl/login");
}
/** * 用戶信息校驗 * @param authentication 信息 * @return 用戶信息 */
@RequestMapping("/user")
public Object user(Authentication authentication) {
return authentication.getPrincipal();
}
/** * 清除Redis中 accesstoken refreshtoken * * @param accesstoken accesstoken * @return true/false */
@PostMapping("/removeToken")
@CacheEvict(value = SecurityConstants.TOKEN_USER_DETAIL, key = "#accesstoken")
public R<Boolean> removeToken(String accesstoken) {
return new R<>( consumerTokenServices.revokeToken(accesstoken));
}
}
複製代碼
接口層有三個接口路徑,第一個應該沒用,剩下兩個是校驗用戶信息的/user
和清除Redis中 accesstoken 與refreshtoken的/removeToken
下面這段代碼時配置各類spring security
配置,包括登錄界面url是"/authentication/require"
啦。若是不使用默認的彈出框而使用本身的頁面,表單的action是"/authentication/form"
啦。使用本身定義的過濾規則啦。禁用csrf
啦(自行搜索csrf,jwt驗證不須要防跨域,可是須要使用xss過濾)。使用手機登錄配置啦。
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER - 1)
@Configuration
@EnableWebSecurity
public class PigSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private FilterIgnorePropertiesConfig filterIgnorePropertiesConfig;
@Autowired
private MobileSecurityConfigurer mobileSecurityConfigurer;
@Override
public void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry =
http.formLogin().loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form")
.and()
.authorizeRequests();
filterIgnorePropertiesConfig.getUrls().forEach(url -> registry.antMatchers(url).permitAll());
registry.anyRequest().authenticated()
.and()
.csrf().disable();
http.apply(mobileSecurityConfigurer);
}
}
複製代碼
讀配置類和接口層,咱們知道了,總的邏輯大概就是用戶登錄了之後,使用spring security框架的認證來獲取權限。
咱們一步一步看,邊猜測邊來。接口處有"ftl/login"
,這大概就是使用freemarker模板,login信息攜帶的token
會傳到用戶信息校驗url"/user"
上,可做者直接使用Authentication
返回一個getPrincipal()
,就沒了,根本沒看見自定義的代碼,這是怎麼回事呢?
原來,做者使用spring security
框架,使用框架來實現校驗信息。
打卡config
包下的PigAuthorizationConfig
,咱們來一探究竟。
註明,閱讀此處模塊須要OAUTH基礎,blog.tengshe789.tech/2018/12/02/…
這裏簡單提一下,spring security oauth
裏有兩個概念,受權服務器和資源服務器。
受權服務器是根據受權許可給訪問的客戶端發放access token
令牌的,提供認證、受權服務;
資源服務器須要驗證這個access token
,客戶端才能訪問對應服務。
ClientDetailsServiceConfigurer
(AuthorizationServerConfigurer
的一個回調配置項) 可以使用內存或者JDBC來實現客戶端詳情服務(ClientDetailsService),Spring Security OAuth2
的配置方法是編寫@Configuration
類繼承AuthorizationServerConfigurerAdapter
,而後重寫void configure(ClientDetailsServiceConfigurer clients)
方法
下面代碼主要邏輯是,使用spring security
框架封裝的簡單sql鏈接器,查詢客戶端的詳細信息👇
@Override
public void configure(` clients) throws Exception {
JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
clientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
clientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
clients.withClientDetails(clientDetailsService);
}
複製代碼
相關的sql語句以下,因爲耦合度較大,我將sql聲明語句改了一改,方面閱讀:
/** * 默認的查詢語句 */
String DEFAULT_FIND_STATEMENT = "select " + "client_id, client_secret, resource_ids, scope, "
+ "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, "
+ "refresh_token_validity, additional_information, autoapprove"
+ " from sys_oauth_client_details" + " order by client_id";
/** * 按條件client_id 查詢 */
String DEFAULT_SELECT_STATEMENT = "select " +"client_id, client_secret, resource_ids, scope, "
+ "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, "
+ "refresh_token_validity, additional_information, autoapprove"
+ " from sys_oauth_client_details" + " where client_id = ?";
複製代碼
相關數據庫信息以下:
endpoints
參數是什麼?全部獲取令牌的請求都將會在Spring MVC controller endpoints
中進行處理
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
//token加強配置
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(
Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));
endpoints
.tokenStore(redisTokenStore())
.tokenEnhancer(tokenEnhancerChain)
.authenticationManager(authenticationManager)
.reuseRefreshTokens(false)
.userDetailsService(userDetailsService);
}
複製代碼
有時候須要額外的信息加到token返回中,這部分也能夠自定義,此時咱們能夠自定義一個TokenEnhancer
,來自定義生成token攜帶的信息。TokenEnhancer
接口提供一個 enhance(OAuth2AccessToken var1, OAuth2Authentication var2)
方法,用於對token信息的添加,信息來源於OAuth2Authentication
。
做者將生成的accessToken
中,加上了本身的名字,加上了userId
@Bean
public TokenEnhancer tokenEnhancer() {
return (accessToken, authentication) -> {
final Map<String, Object> additionalInfo = new HashMap<>(2);
additionalInfo.put("license", SecurityConstants.PIG_LICENSE);
UserDetailsImpl user = (UserDetailsImpl) authentication.getUserAuthentication().getPrincipal();
if (user != null) {
additionalInfo.put("userId", user.getUserId());
}
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
};
}
複製代碼
JWT中,須要在token中攜帶額外的信息,這樣能夠在服務之間共享部分用戶信息,spring security默認在JWT的token中加入了user_name,若是咱們須要額外的信息,須要自定義這部份內容。
JwtAccessTokenConverter
是使用JWT
替換默認的Token的轉換器,而token令牌默認是有簽名的,且資源服務器須要驗證這個簽名。此處的加密及驗籤包括兩種方式:
對稱加密
非對稱加密(公鑰密鑰)
對稱加密須要受權服務器和資源服務器存儲同一key值,而非對稱加密可以使用密鑰加密,暴露公鑰給資源服務器驗籤
public class PigJwtAccessTokenConverter extends JwtAccessTokenConverter {
@Override
public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
Map<String, Object> representation = (Map<String, Object>) super.convertAccessToken(token, authentication);
representation.put("license", SecurityConstants.PIG_LICENSE);
return representation;
}
@Override
public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) {
return super.extractAccessToken(value, map);
}
@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
return super.extractAuthentication(map);
}
}
複製代碼
使用鑑權的endpoint
將加上本身名字的token
放入redis
,redis鏈接器用的srping data redis
框架
/** * tokenstore 定製化處理 * * @return TokenStore * 1. 若是使用的 redis-cluster 模式請使用 PigRedisTokenStore * PigRedisTokenStore tokenStore = new PigRedisTokenStore(); * tokenStore.setRedisTemplate(redisTemplate); */
@Bean
public TokenStore redisTokenStore() {
RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
tokenStore.setPrefix(SecurityConstants.PIG_PREFIX);
return tokenStore;
}
複製代碼
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.allowFormAuthenticationForClients()
.tokenKeyAccess("isAuthenticated()")
.checkTokenAccess("permitAll()");
}
複製代碼
先看接口層,這裏和pig-upms-service
聯動,給了三個路徑,用戶使用手機號碼登錄可經過三個路徑發送請求
@FeignClient(name = "pig-upms-service", fallback = UserServiceFallbackImpl.class)
public interface UserService {
/** * 經過用戶名查詢用戶、角色信息 * * @param username 用戶名 * @return UserVo */
@GetMapping("/user/findUserByUsername/{username}")
UserVO findUserByUsername(@PathVariable("username") String username);
/** * 經過手機號查詢用戶、角色信息 * * @param mobile 手機號 * @return UserVo */
@GetMapping("/user/findUserByMobile/{mobile}")
UserVO findUserByMobile(@PathVariable("mobile") String mobile);
/** * 根據OpenId查詢用戶信息 * @param openId openId * @return UserVo */
@GetMapping("/user/findUserByOpenId/{openId}")
UserVO findUserByOpenId(@PathVariable("openId") String openId);
}
複製代碼
重寫SecurityConfigurerAdapter
的方法,經過http請求,找出有關手機號的token,用token找出相關用戶的信息,已Authentication
方式保存。拿到信息後,使用過濾器驗證
@Component
public class MobileSecurityConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
@Autowired
private AuthenticationSuccessHandler mobileLoginSuccessHandler;
@Autowired
private UserService userService;
@Override
public void configure(HttpSecurity http) throws Exception {
MobileAuthenticationFilter mobileAuthenticationFilter = new MobileAuthenticationFilter();
mobileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
mobileAuthenticationFilter.setAuthenticationSuccessHandler(mobileLoginSuccessHandler);
MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider();
mobileAuthenticationProvider.setUserService(userService);
http.authenticationProvider(mobileAuthenticationProvider)
.addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
複製代碼
在spring security
中,AuthenticationManage
管理一系列的AuthenticationProvider
, 而每個Provider
都會通UserDetailsService
和UserDetail
來返回一個 以MobileAuthenticationToken
實現的帶用戶以及權限的Authentication
此處邏輯是,經過UserService
查找已有用戶的手機號碼,生成對應的UserDetails
,使用UserDetails生成手機驗證Authentication
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication;
UserVO userVo = userService.findUserByMobile((String) mobileAuthenticationToken.getPrincipal());
if (userVo == null) {
throw new UsernameNotFoundException("手機號不存在:" + mobileAuthenticationToken.getPrincipal());
}
UserDetailsImpl userDetails = buildUserDeatils(userVo);
MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities());
authenticationToken.setDetails(mobileAuthenticationToken.getDetails());
return authenticationToken;
}
private UserDetailsImpl buildUserDeatils(UserVO userVo) {
return new UserDetailsImpl(userVo);
}
@Override
public boolean supports(Class<?> authentication) {
return MobileAuthenticationToken.class.isAssignableFrom(authentication);
}
複製代碼
MobileAuthenticationToken
繼承AbstractAuthenticationToken
實現Authentication
因此當在頁面中輸入手機以後首先會進入到MobileAuthenticationToken
驗證(Authentication), 而後生成的Authentication
會被交由我上面說的AuthenticationManager
來進行管理
public class MobileAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Object principal;
public MobileAuthenticationToken(String mobile) {
super(null);
this.principal = mobile;
setAuthenticated(false);
}
public MobileAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
super.setAuthenticated(true);
}
@Override
public Object getPrincipal() {
return this.principal;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
if (isAuthenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
}
super.setAuthenticated(false);
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
}
}
複製代碼
判斷http請求是不是post,不是則返回錯誤。
根據request請求拿到moblie信息,使用moblie信息返回手機號碼登錄成功的oauth token。
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String mobile = obtainMobile(request);
if (mobile == null) {
mobile = "";
}
mobile = mobile.trim();
MobileAuthenticationToken mobileAuthenticationToken = new MobileAuthenticationToken(mobile);
setDetails(request, mobileAuthenticationToken);
return this.getAuthenticationManager().authenticate(mobileAuthenticationToken);
}
複製代碼
這個處理器能夠返回手機號登陸成功的oauth token
,可是要將oauth token
傳輸出去必須配合上面的手機號登陸驗證filter
邏輯都在註釋中
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith(BASIC_)) {
throw new UnapprovedClientAuthenticationException("請求頭中client信息爲空");
}
try {
String[] tokens = AuthUtils.extractAndDecodeHeader(header);
assert tokens.length == 2;
String clientId = tokens[0];
ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
//校驗secret
if (!clientDetails.getClientSecret().equals(tokens[1])) {
throw new InvalidClientException("Given client ID does not match authenticated client");
}
TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "mobile");
//校驗scope
new DefaultOAuth2RequestValidator().validateScope(tokenRequest, clientDetails);
OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
log.info("獲取token 成功:{}", oAuth2AccessToken.getValue());
response.setCharacterEncoding(CommonConstant.UTF8);
response.setContentType(CommonConstant.CONTENT_TYPE);
PrintWriter printWriter = response.getWriter();
printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
} catch (IOException e) {
throw new BadCredentialsException(
"Failed to decode basic authentication token");
}
}
/** * 從header 請求中的clientId/clientsecect * * @param header header中的參數 * @throws CheckedException if the Basic header is not present or is not valid * Base64 */
public static String[] extractAndDecodeHeader(String header)
throws IOException {
byte[] base64Token = header.substring(6).getBytes("UTF-8");
byte[] decoded;
try {
decoded = Base64.decode(base64Token);
} catch (IllegalArgumentException e) {
throw new CheckedException(
"Failed to decode basic authentication token");
}
String token = new String(decoded, CommonConstant.UTF8);
int delim = token.indexOf(":");
if (delim == -1) {
throw new CheckedException("Invalid basic authentication token");
}
return new String[]{token.substring(0, delim), token.substring(delim + 1)};
}
複製代碼
挺好的模板,收藏一下
public class PigRedisTokenStore implements TokenStore {
private static final String ACCESS = "access:";
private static final String AUTH_TO_ACCESS = "auth_to_access:";
private static final String AUTH = "auth:";
private static final String REFRESH_AUTH = "refresh_auth:";
private static final String ACCESS_TO_REFRESH = "access_to_refresh:";
private static final String REFRESH = "refresh:";
private static final String REFRESH_TO_ACCESS = "refresh_to_access:";
private static final String CLIENT_ID_TO_ACCESS = "client_id_to_access:";
private static final String UNAME_TO_ACCESS = "uname_to_access:";
private RedisTemplate<String, Object> redisTemplate;
public RedisTemplate<String, Object> getRedisTemplate() {
return redisTemplate;
}
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();
public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
this.authenticationKeyGenerator = authenticationKeyGenerator;
}
@Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
String key = authenticationKeyGenerator.extractKey(authentication);
OAuth2AccessToken accessToken = (OAuth2AccessToken) redisTemplate.opsForValue().get(AUTH_TO_ACCESS + key);
if (accessToken != null
&& !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) {
storeAccessToken(accessToken, authentication);
}
return accessToken;
}
@Override
public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
return readAuthentication(token.getValue());
}
@Override
public OAuth2Authentication readAuthentication(String token) {
return (OAuth2Authentication) this.redisTemplate.opsForValue().get(AUTH + token);
}
@Override
public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
return readAuthenticationForRefreshToken(token.getValue());
}
public OAuth2Authentication readAuthenticationForRefreshToken(String token) {
return (OAuth2Authentication) this.redisTemplate.opsForValue().get(REFRESH_AUTH + token);
}
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
this.redisTemplate.opsForValue().set(ACCESS + token.getValue(), token);
this.redisTemplate.opsForValue().set(AUTH + token.getValue(), authentication);
this.redisTemplate.opsForValue().set(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), token);
if (!authentication.isClientOnly()) {
redisTemplate.opsForList().rightPush(UNAME_TO_ACCESS + getApprovalKey(authentication), token);
}
redisTemplate.opsForList().rightPush(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), token);
if (token.getExpiration() != null) {
int seconds = token.getExpiresIn();
redisTemplate.expire(ACCESS + token.getValue(), seconds, TimeUnit.SECONDS);
redisTemplate.expire(AUTH + token.getValue(), seconds, TimeUnit.SECONDS);
redisTemplate.expire(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), seconds, TimeUnit.SECONDS);
redisTemplate.expire(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, TimeUnit.SECONDS);
redisTemplate.expire(UNAME_TO_ACCESS + getApprovalKey(authentication), seconds, TimeUnit.SECONDS);
}
if (token.getRefreshToken() != null && token.getRefreshToken().getValue() != null) {
this.redisTemplate.opsForValue().set(REFRESH_TO_ACCESS + token.getRefreshToken().getValue(), token.getValue());
this.redisTemplate.opsForValue().set(ACCESS_TO_REFRESH + token.getValue(), token.getRefreshToken().getValue());
}
}
private String getApprovalKey(OAuth2Authentication authentication) {
String userName = authentication.getUserAuthentication() == null ? "" : authentication.getUserAuthentication()
.getName();
return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
}
private String getApprovalKey(String clientId, String userName) {
return clientId + (userName == null ? "" : ":" + userName);
}
@Override
public void removeAccessToken(OAuth2AccessToken accessToken) {
removeAccessToken(accessToken.getValue());
}
@Override
public OAuth2AccessToken readAccessToken(String tokenValue) {
return (OAuth2AccessToken) this.redisTemplate.opsForValue().get(ACCESS + tokenValue);
}
public void removeAccessToken(String tokenValue) {
OAuth2AccessToken removed = (OAuth2AccessToken) redisTemplate.opsForValue().get(ACCESS + tokenValue);
// caller to do that
OAuth2Authentication authentication = (OAuth2Authentication) this.redisTemplate.opsForValue().get(AUTH + tokenValue);
this.redisTemplate.delete(AUTH + tokenValue);
redisTemplate.delete(ACCESS + tokenValue);
this.redisTemplate.delete(ACCESS_TO_REFRESH + tokenValue);
if (authentication != null) {
this.redisTemplate.delete(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
String clientId = authentication.getOAuth2Request().getClientId();
redisTemplate.opsForList().leftPop(UNAME_TO_ACCESS + getApprovalKey(clientId, authentication.getName()));
redisTemplate.opsForList().leftPop(CLIENT_ID_TO_ACCESS + clientId);
this.redisTemplate.delete(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
}
}
@Override
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
this.redisTemplate.opsForValue().set(REFRESH + refreshToken.getValue(), refreshToken);
this.redisTemplate.opsForValue().set(REFRESH_AUTH + refreshToken.getValue(), authentication);
}
@Override
public OAuth2RefreshToken readRefreshToken(String tokenValue) {
return (OAuth2RefreshToken) this.redisTemplate.opsForValue().get(REFRESH + tokenValue);
}
@Override
public void removeRefreshToken(OAuth2RefreshToken refreshToken) {
removeRefreshToken(refreshToken.getValue());
}
public void removeRefreshToken(String tokenValue) {
this.redisTemplate.delete(REFRESH + tokenValue);
this.redisTemplate.delete(REFRESH_AUTH + tokenValue);
this.redisTemplate.delete(REFRESH_TO_ACCESS + tokenValue);
}
@Override
public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
removeAccessTokenUsingRefreshToken(refreshToken.getValue());
}
private void removeAccessTokenUsingRefreshToken(String refreshToken) {
String token = (String) this.redisTemplate.opsForValue().get(REFRESH_TO_ACCESS + refreshToken);
if (token != null) {
redisTemplate.delete(ACCESS + token);
}
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
List<Object> result = redisTemplate.opsForList().range(UNAME_TO_ACCESS + getApprovalKey(clientId, userName), 0, -1);
if (result == null || result.size() == 0) {
return Collections.emptySet();
}
List<OAuth2AccessToken> accessTokens = new ArrayList<>(result.size());
for (Iterator<Object> it = result.iterator(); it.hasNext(); ) {
OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next();
accessTokens.add(accessToken);
}
return Collections.unmodifiableCollection(accessTokens);
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
List<Object> result = redisTemplate.opsForList().range((CLIENT_ID_TO_ACCESS + clientId), 0, -1);
if (result == null || result.size() == 0) {
return Collections.emptySet();
}
List<OAuth2AccessToken> accessTokens = new ArrayList<>(result.size());
for (Iterator<Object> it = result.iterator(); it.hasNext(); ) {
OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next();
accessTokens.add(accessToken);
}
return Collections.unmodifiableCollection(accessTokens);
}
}
複製代碼
網關主體在包pig\pig-gateway\src\main\java\com\github\pig\gateway
下
做者使用了Zuul作爲網關,它Netflix開源的微服務網關,能夠和Eureka,Ribbon,Hystrix等組件配合使用。
Zuul組件的核心是一系列的過濾器,這些過濾器能夠完成如下功能:
身份認證和安全: 識別每個資源的驗證要求,並拒絕那些不符的請求
審查與監控:
動態路由:動態將請求路由到不一樣後端集羣
壓力測試:逐漸增長指向集羣的流量,以瞭解性能
負載分配:爲每一種負載類型分配對應容量,並棄用超出限定值的請求
靜態響應處理:邊緣位置進行響應,避免轉發到內部集羣
多區域彈性:跨域AWS Region進行請求路由,旨在實現ELB(ElasticLoad Balancing)使用多樣化
Zuul組件的核心是一系列的過濾器,咱們先從過濾器下手。
@Component
public class ErrorHandlerFilter extends ZuulFilter {
@Autowired
private LogSendService logSendService;
@Override
public String filterType() {
return ERROR_TYPE;
}
@Override
public int filterOrder() {
return SEND_RESPONSE_FILTER_ORDER + 1;
}
@Override
public boolean shouldFilter() {
RequestContext requestContext = RequestContext.getCurrentContext();
return requestContext.getThrowable() != null;
}
@Override
public Object run() {
RequestContext requestContext = RequestContext.getCurrentContext();
logSendService.send(requestContext);
return null;
}
}
複製代碼
做者以原生zuul過濾器爲基礎加了日誌配置,優先級爲+1,數字越大優先級越低。
public class XssSecurityFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(request);
filterChain.doFilter(xssRequest, response);
}
複製代碼
重寫springMVC裏面的的確保在一次請求只經過一次filter的類OncePerRequestFilter
,添加一條https://gitee.com/renrenio/renren-fast的工具類XssHttpServletRequestWrapper
爲過濾鏈條。
@Override
public ServletInputStream getInputStream() throws IOException {
····略
//xss過濾
json = xssEncode(json);
final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8"));
return new ServletInputStream() {
···略
}
};
}
複製代碼
此過濾器優先級爲+2.每當一個請求不是請求/oauth/token
或者/mobile/token
這個地址時,都會解析使用aes解碼器password
。
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
Map<String, List<String>> params = ctx.getRequestQueryParams();
if (params == null) {
return null;
}
List<String> passList = params.get(PASSWORD);
if (CollUtil.isEmpty(passList)) {
return null;
}
String password = passList.get(0);
if (StrUtil.isNotBlank(password)) {
try {
password = decryptAES(password, key);
} catch (Exception e) {
log.error("密碼解密失敗:{}", password);
}
params.put(PASSWORD, CollUtil.newArrayList(password.trim()));
}
ctx.setRequestQueryParams(params);
return null;
}
複製代碼
邏輯做者都寫在註釋中了,此處使用了redis作爲服務端驗證碼的緩存
**
* 是否校驗驗證碼
* 1. 判斷驗證碼開關是否開啓
* 2. 判斷請求是否登陸請求
* 2.1 判斷是否是刷新請求(不用單獨在創建刷新客戶端)
* 3. 判斷終端是否支持
*
* @return true/false
*/
@Override
public boolean shouldFilter() {
HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
if (!StrUtil.containsAnyIgnoreCase(request.getRequestURI(),
SecurityConstants.OAUTH_TOKEN_URL, SecurityConstants.MOBILE_TOKEN_URL)) {
return false;
}
if (SecurityConstants.REFRESH_TOKEN.equals(request.getParameter(GRANT_TYPE))) {
return false;
}
try {
String[] clientInfos = AuthUtils.extractAndDecodeHeader(request);
if (CollUtil.containsAny(filterIgnorePropertiesConfig.getClients(), Arrays.asList(clientInfos))) {
return false;
}
} catch (IOException e) {
log.error("解析終端信息失敗", e);
}
return true;
}
@Override
public Object run() {
try {
checkCode(RequestContext.getCurrentContext().getRequest());
} catch (ValidateCodeException e) {
RequestContext ctx = RequestContext.getCurrentContext();
R<String> result = new R<>(e);
result.setCode(478);
ctx.setResponseStatusCode(478);
ctx.setSendZuulResponse(false);
ctx.getResponse().setContentType("application/json;charset=UTF-8");
ctx.setResponseBody(JSONObject.toJSONString(result));
}
return null;
}
/** * 檢查code * * @param httpServletRequest request * @throws ValidateCodeException 驗證碼校驗異常 */
private void checkCode(HttpServletRequest httpServletRequest) throws ValidateCodeException {
String code = httpServletRequest.getParameter("code");
if (StrUtil.isBlank(code)) {
throw new ValidateCodeException("請輸入驗證碼");
}
String randomStr = httpServletRequest.getParameter("randomStr");
if (StrUtil.isBlank(randomStr)) {
randomStr = httpServletRequest.getParameter("mobile");
}
String key = SecurityConstants.DEFAULT_CODE_KEY + randomStr;
if (!redisTemplate.hasKey(key)) {
throw new ValidateCodeException(EXPIRED_CAPTCHA_ERROR);
}
Object codeObj = redisTemplate.opsForValue().get(key);
if (codeObj == null) {
throw new ValidateCodeException(EXPIRED_CAPTCHA_ERROR);
}
String saveCode = codeObj.toString();
if (StrUtil.isBlank(saveCode)) {
redisTemplate.delete(key);
throw new ValidateCodeException(EXPIRED_CAPTCHA_ERROR);
}
if (!StrUtil.equals(saveCode, code)) {
redisTemplate.delete(key);
throw new ValidateCodeException("驗證碼錯誤,請從新輸入");
}
redisTemplate.delete(key);
}
複製代碼
灰度發佈,已經不是一個很新的概念了.一個產品,若是須要快速迭代開發上線,又要保證質量,保證剛上線的系統,一旦出現問題那麼能夠很快的控制影響面,就須要設計一套灰度發佈系統.
灰度發佈系統的做用在於,能夠根據本身的配置,來將用戶的流量導到新上線的系統上,來快速驗證新的功能修改,而一旦出問題,也能夠立刻的恢復,簡單的說,就是一套A/BTest系統.
下面是灰度路由初始化類:
@Configuration
@ConditionalOnClass(DiscoveryEnabledNIWSServerList.class)
@AutoConfigureBefore(RibbonClientConfiguration.class)
@ConditionalOnProperty(value = "zuul.ribbon.metadata.enabled")
public class RibbonMetaFilterAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public ZoneAvoidanceRule metadataAwareRule() {
return new MetadataCanaryRuleHandler();
}
}
複製代碼
首先重寫filterOrder()
方法,使這個過濾器在在RateLimitPreFilter
以前運行,不會出現空指針問題。此處優先級FORM_BODY_WRAPPER_FILTER_ORDER-1
.
@Component
public class AccessFilter extends ZuulFilter {
@Value("${zuul.ribbon.metadata.enabled:false}")
private boolean canary;
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
@Override
public int filterOrder() {
return FORM_BODY_WRAPPER_FILTER_ORDER - 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext requestContext = RequestContext.getCurrentContext();
String version = requestContext.getRequest().getHeader(SecurityConstants.VERSION);
if (canary && StrUtil.isNotBlank(version)) {
RibbonVersionHolder.setContext(version);
}
requestContext.set("startTime", System.currentTimeMillis());
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
requestContext.addZuulRequestHeader(SecurityConstants.USER_HEADER, authentication.getName());
requestContext.addZuulRequestHeader(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ","));
}
return null;
}
}
複製代碼
核心方法在run()上,首先受到request請求,拿到他的版本約束信息,而後根據選擇添加token
自定義ribbon
路由規則匹配多版本請求,實現灰度發佈。複合判斷server所在區域的性能和server的可用性選擇server,即,使用ZoneAvoidancePredicate和AvailabilityPredicate來判斷是否選擇某個server,前一個判斷斷定一個zone的運行性能是否可用,剔除不可用的zone(的全部server),AvailabilityPredicate用於過濾掉鏈接數過多的Server。
此處邏輯是
@Override
public AbstractServerPredicate getPredicate() {
return new AbstractServerPredicate() {
@Override
public boolean apply(PredicateKey predicateKey) {
String targetVersion = RibbonVersionHolder.getContext();
RibbonVersionHolder.clearContext();
if (StrUtil.isBlank(targetVersion)) {
log.debug("客戶端未配置目標版本直接路由");
return true;
}
DiscoveryEnabledServer server = (DiscoveryEnabledServer) predicateKey.getServer();
final Map<String, String> metadata = server.getInstanceInfo().getMetadata();
if (StrUtil.isBlank(metadata.get(SecurityConstants.VERSION))) {
log.debug("當前微服務{} 未配置版本直接路由");
return true;
}
if (metadata.get(SecurityConstants.VERSION).equals(targetVersion)) {
return true;
} else {
log.debug("當前微服務{} 版本爲{},目標版本{} 匹配失敗", server.getInstanceInfo().getAppName()
, metadata.get(SecurityConstants.VERSION), targetVersion);
return false;
}
}
};
}
複製代碼
public class DynamicRouteLocator extends DiscoveryClientRouteLocator {
private ZuulProperties properties;
private RedisTemplate redisTemplate;
public DynamicRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties, ServiceInstance localServiceInstance, RedisTemplate redisTemplate) {
super(servletPath, discovery, properties, localServiceInstance);
this.properties = properties;
this.redisTemplate = redisTemplate;
}
/** * 重寫路由配置 * <p> * 1. properties 配置。 * 2. eureka 默認配置。 * 3. DB數據庫配置。 * * @return 路由表 */
@Override
protected LinkedHashMap<String, ZuulProperties.ZuulRoute> locateRoutes() {
LinkedHashMap<String, ZuulProperties.ZuulRoute> routesMap = new LinkedHashMap<>();
//讀取properties配置、eureka默認配置
routesMap.putAll(super.locateRoutes());
log.debug("初始默認的路由配置完成");
routesMap.putAll(locateRoutesFromDb());
LinkedHashMap<String, ZuulProperties.ZuulRoute> values = new LinkedHashMap<>();
for (Map.Entry<String, ZuulProperties.ZuulRoute> entry : routesMap.entrySet()) {
String path = entry.getKey();
if (!path.startsWith("/")) {
path = "/" + path;
}
if (StrUtil.isNotBlank(this.properties.getPrefix())) {
path = this.properties.getPrefix() + path;
if (!path.startsWith("/")) {
path = "/" + path;
}
}
values.put(path, entry.getValue());
}
return values;
}
/** * Redis中保存的,沒有從upms拉去,避免啓動鏈路依賴問題(取捨),網關依賴業務模塊的問題 * * @return */
private Map<String, ZuulProperties.ZuulRoute> locateRoutesFromDb() {
Map<String, ZuulProperties.ZuulRoute> routes = new LinkedHashMap<>();
Object obj = redisTemplate.opsForValue().get(CommonConstant.ROUTE_KEY);
if (obj == null) {
return routes;
}
List<SysZuulRoute> results = (List<SysZuulRoute>) obj;
for (SysZuulRoute result : results) {
if (StrUtil.isBlank(result.getPath()) && StrUtil.isBlank(result.getUrl())) {
continue;
}
ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
try {
zuulRoute.setId(result.getServiceId());
zuulRoute.setPath(result.getPath());
zuulRoute.setServiceId(result.getServiceId());
zuulRoute.setRetryable(StrUtil.equals(result.getRetryable(), "0") ? Boolean.FALSE : Boolean.TRUE);
zuulRoute.setStripPrefix(StrUtil.equals(result.getStripPrefix(), "0") ? Boolean.FALSE : Boolean.TRUE);
zuulRoute.setUrl(result.getUrl());
List<String> sensitiveHeadersList = StrUtil.splitTrim(result.getSensitiveheadersList(), ",");
if (sensitiveHeadersList != null) {
Set<String> sensitiveHeaderSet = CollUtil.newHashSet();
sensitiveHeadersList.forEach(sensitiveHeader -> sensitiveHeaderSet.add(sensitiveHeader));
zuulRoute.setSensitiveHeaders(sensitiveHeaderSet);
zuulRoute.setCustomSensitiveHeaders(true);
}
} catch (Exception e) {
log.error("從數據庫加載路由配置異常", e);
}
log.debug("添加數據庫自定義的路由配置,path:{},serviceId:{}", zuulRoute.getPath(), zuulRoute.getServiceId());
routes.put(zuulRoute.getPath(), zuulRoute);
}
return routes;
}
}
複製代碼
代碼註釋已經將邏輯寫的很清楚了
@Slf4j
@Component
public class LogSendServiceImpl implements LogSendService {
private static final String SERVICE_ID = "serviceId";
@Autowired
private AmqpTemplate rabbitTemplate;
/** * 1. 獲取 requestContext 中的請求信息 * 2. 若是返回狀態不是OK,則獲取返回信息中的錯誤信息 * 3. 發送到MQ * * @param requestContext 上下文對象 */
@Override
public void send(RequestContext requestContext) {
HttpServletRequest request = requestContext.getRequest();
String requestUri = request.getRequestURI();
String method = request.getMethod();
SysLog sysLog = new SysLog();
sysLog.setType(CommonConstant.STATUS_NORMAL);
sysLog.setRemoteAddr(HttpUtil.getClientIP(request));
sysLog.setRequestUri(URLUtil.getPath(requestUri));
sysLog.setMethod(method);
sysLog.setUserAgent(request.getHeader("user-agent"));
sysLog.setParams(HttpUtil.toParams(request.getParameterMap()));
Long startTime = (Long) requestContext.get("startTime");
sysLog.setTime(System.currentTimeMillis() - startTime);
if (requestContext.get(SERVICE_ID) != null) {
sysLog.setServiceId(requestContext.get(SERVICE_ID).toString());
}
//正常發送服務異常解析
if (requestContext.getResponseStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR
&& requestContext.getResponseDataStream() != null) {
InputStream inputStream = requestContext.getResponseDataStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream stream1 = null;
InputStream stream2;
byte[] buffer = IoUtil.readBytes(inputStream);
try {
baos.write(buffer);
baos.flush();
stream1 = new ByteArrayInputStream(baos.toByteArray());
stream2 = new ByteArrayInputStream(baos.toByteArray());
String resp = IoUtil.read(stream1, CommonConstant.UTF8);
sysLog.setType(CommonConstant.STATUS_LOCK);
sysLog.setException(resp);
requestContext.setResponseDataStream(stream2);
} catch (IOException e) {
log.error("響應流解析異常:", e);
throw new RuntimeException(e);
} finally {
IoUtil.close(stream1);
IoUtil.close(baos);
IoUtil.close(inputStream);
}
}
//網關內部異常
Throwable throwable = requestContext.getThrowable();
if (throwable != null) {
log.error("網關異常", throwable);
sysLog.setException(throwable.getMessage());
}
//保存發往MQ(只保存受權)
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && StrUtil.isNotBlank(authentication.getName())) {
LogVO logVo = new LogVO();
sysLog.setCreateBy(authentication.getName());
logVo.setSysLog(sysLog);
logVo.setUsername(authentication.getName());
rabbitTemplate.convertAndSend(MqQueueConstant.LOG_QUEUE, logVo);
}
}
}
複製代碼
重寫zuul中默認的限流處理器DefaultRateLimiterErrorHandler
,使之記錄日誌內容
@Bean
public RateLimiterErrorHandler rateLimitErrorHandler() {
return new DefaultRateLimiterErrorHandler() {
@Override
public void handleSaveError(String key, Exception e) {
log.error("保存key:[{}]異常", key, e);
}
@Override
public void handleFetchError(String key, Exception e) {
log.error("路由失敗:[{}]異常", key);
}
@Override
public void handleError(String msg, Exception e) {
log.error("限流異常:[{}]", msg, e);
}
};
}
複製代碼
重寫Srping security oAuth
提供單點登陸驗證拒絕OAuth2AccessDeniedHandler
接口,使用R包裝失敗信息到PigDeniedException
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
log.info("受權失敗,禁止訪問 {}", request.getRequestURI());
response.setCharacterEncoding(CommonConstant.UTF8);
response.setContentType(CommonConstant.CONTENT_TYPE);
R<String> result = new R<>(new PigDeniedException("受權失敗,禁止訪問"));
response.setStatus(HttpStatus.SC_FORBIDDEN);
PrintWriter printWriter = response.getWriter();
printWriter.append(objectMapper.writeValueAsString(result));
}
複製代碼
@FeignClient(name = "pig-upms-service", fallback = MenuServiceFallbackImpl.class)
public interface MenuService {
/** * 經過角色名查詢菜單 * * @param role 角色名稱 * @return 菜單列表 */
@GetMapping(value = "/menu/findMenuByRole/{role}")
Set<MenuVO> findMenuByRole(@PathVariable("role") String role);
}
複製代碼
使用feign鏈接pig系統的菜單微服務
@Service("permissionService")
public class PermissionServiceImpl implements PermissionService {
@Autowired
private MenuService menuService;
private AntPathMatcher antPathMatcher = new AntPathMatcher();
@Override
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
//ele-admin options 跨域配置,如今處理是經過前端配置代理,不使用這種方式,存在風險
// if (HttpMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod())) {
// return true;
// }
Object principal = authentication.getPrincipal();
List<SimpleGrantedAuthority> authorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
AtomicBoolean hasPermission = new AtomicBoolean(false);
if (principal != null) {
if (CollUtil.isEmpty(authorityList)) {
log.warn("角色列表爲空:{}", authentication.getPrincipal());
return false;
}
Set<MenuVO> urls = new HashSet<>();
authorityList.stream().filter(authority ->
!StrUtil.equals(authority.getAuthority(), "ROLE_USER"))
.forEach(authority -> {
Set<MenuVO> menuVOSet = menuService.findMenuByRole(authority.getAuthority());
CollUtil.addAll(urls, menuVOSet);
});
urls.stream().filter(menu -> StrUtil.isNotEmpty(menu.getUrl())
&& antPathMatcher.match(menu.getUrl(), request.getRequestURI())
&& request.getMethod().equalsIgnoreCase(menu.getMethod()))
.findFirst().ifPresent(menuVO -> hasPermission.set(true));
}
return hasPermission.get();
}
}
複製代碼
pig這個系統是個很好的框架,本次體驗的是pig的zuul網關模塊,此模塊與feign,ribbon,spring security,Eurasia進行整合,完成或部分完成了動態路由,灰度發佈,菜單權限管理,服務限流,網關日誌處理,很是值得學習!
百度了一下,UPMS是User Permissions Management System,通用用戶權限管理系統
/** * 編號 */
@TableId(value="id", type= IdType.AUTO)
private Integer id;
/** * 數據值 */
private String value;
/** * 標籤名 */
private String label;
/** * 類型 */
private String type;
/** * 描述 */
private String description;
/** * 排序(升序) */
private BigDecimal sort;
/** * 建立時間 */
@TableField("create_time")
private Date createTime;
/** * 更新時間 */
@TableField("update_time")
private Date updateTime;
/** * 備註信息 */
private String remarks;
/** * 刪除標記 */
@TableField("del_flag")
private String delFlag;
複製代碼
@Data
public class SysLog implements Serializable {
private static final long serialVersionUID = 1L;
/** * 編號 */
@TableId(type = IdType.ID_WORKER)
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
/** * 日誌類型 */
private String type;
/** * 日誌標題 */
private String title;
/** * 建立者 */
private String createBy;
/** * 建立時間 */
private Date createTime;
/** * 更新時間 */
private Date updateTime;
/** * 操做IP地址 */
private String remoteAddr;
/** * 用戶代理 */
private String userAgent;
/** * 請求URI */
private String requestUri;
/** * 操做方式 */
private String method;
/** * 操做提交的數據 */
private String params;
/** * 執行時間 */
private Long time;
/** * 刪除標記 */
private String delFlag;
/** * 異常信息 */
private String exception;
/** * 服務ID */
private String serviceId; }}
複製代碼
略
略
/** * 主鍵ID */
@TableId(value = "user_id", type = IdType.AUTO)
private Integer userId;
/** * 用戶名 */
private String username;
private String password;
/** * 隨機鹽 */
@JsonIgnore
private String salt;
/** * 建立時間 */
@TableField("create_time")
private Date createTime;
/** * 修改時間 */
@TableField("update_time")
private Date updateTime;
/** * 0-正常,1-刪除 */
@TableField("del_flag")
private String delFlag;
/** * 簡介 */
private String phone;
/** * 頭像 */
private String avatar;
/** * 部門ID */
@TableField("dept_id")
private Integer deptId;
複製代碼
全是基於mybatis plus的CRUD,有點多。大部分幹這行的都懂,我就不詳細展開了。
ValidateCodeController
能夠找到建立驗證碼相關代碼
/** * 建立驗證碼 * * @param request request * @throws Exception */
@GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{randomStr}")
public void createCode(@PathVariable String randomStr, HttpServletRequest request, HttpServletResponse response) throws Exception {
Assert.isBlank(randomStr, "機器碼不能爲空");
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
//生成文字驗證碼
String text = producer.createText();
//生成圖片驗證碼
BufferedImage image = producer.createImage(text);
userService.saveImageCode(randomStr, text);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "JPEG", out);
IOUtils.closeQuietly(out);
}
複製代碼
其中的 producer
是使用Kaptcha
,下面是配置類
@Configuration
public class KaptchaConfig {
private static final String KAPTCHA_BORDER = "kaptcha.border";
private static final String KAPTCHA_TEXTPRODUCER_FONT_COLOR = "kaptcha.textproducer.font.color";
private static final String KAPTCHA_TEXTPRODUCER_CHAR_SPACE = "kaptcha.textproducer.char.space";
private static final String KAPTCHA_IMAGE_WIDTH = "kaptcha.image.width";
private static final String KAPTCHA_IMAGE_HEIGHT = "kaptcha.image.height";
private static final String KAPTCHA_TEXTPRODUCER_CHAR_LENGTH = "kaptcha.textproducer.char.length";
private static final Object KAPTCHA_IMAGE_FONT_SIZE = "kaptcha.textproducer.font.size";
@Bean
public DefaultKaptcha producer() {
Properties properties = new Properties();
properties.put(KAPTCHA_BORDER, SecurityConstants.DEFAULT_IMAGE_BORDER);
properties.put(KAPTCHA_TEXTPRODUCER_FONT_COLOR, SecurityConstants.DEFAULT_COLOR_FONT);
properties.put(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, SecurityConstants.DEFAULT_CHAR_SPACE);
properties.put(KAPTCHA_IMAGE_WIDTH, SecurityConstants.DEFAULT_IMAGE_WIDTH);
properties.put(KAPTCHA_IMAGE_HEIGHT, SecurityConstants.DEFAULT_IMAGE_HEIGHT);
properties.put(KAPTCHA_IMAGE_FONT_SIZE, SecurityConstants.DEFAULT_IMAGE_FONT_SIZE);
properties.put(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, SecurityConstants.DEFAULT_IMAGE_LENGTH);
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
複製代碼
大致邏輯爲,先查詢驗證碼redis緩存,沒有緩存則說明驗證碼緩存沒有失效,返回錯誤。
查到沒有驗證碼,則根據手機號碼從數據庫得到用戶信息,生成一個4位的驗證碼,使用rabbbitmq
隊列把短信驗證碼保存到隊列,同時加上手機驗證碼的redis緩存
/** * 發送驗證碼 * <p> * 1. 先去redis 查詢是否 60S內已經發送 * 2. 未發送: 判斷手機號是否存 ? false :產生4位數字 手機號-驗證碼 * 3. 發往消息中心-》發送信息 * 4. 保存redis * * @param mobile 手機號 * @return true、false */
@Override
public R<Boolean> sendSmsCode(String mobile) {
Object tempCode = redisTemplate.opsForValue().get(SecurityConstants.DEFAULT_CODE_KEY + mobile);
if (tempCode != null) {
log.error("用戶:{}驗證碼未失效{}", mobile, tempCode);
return new R<>(false, "驗證碼未失效,請失效後再次申請");
}
SysUser params = new SysUser();
params.setPhone(mobile);
List<SysUser> userList = this.selectList(new EntityWrapper<>(params));
if (CollectionUtil.isEmpty(userList)) {
log.error("根據用戶手機號{}查詢用戶爲空", mobile);
return new R<>(false, "手機號不存在");
}
String code = RandomUtil.randomNumbers(4);
JSONObject contextJson = new JSONObject();
contextJson.put("code", code);
contextJson.put("product", "Pig4Cloud");
log.info("短信發送請求消息中心 -> 手機號:{} -> 驗證碼:{}", mobile, code);
rabbitTemplate.convertAndSend(MqQueueConstant.MOBILE_CODE_QUEUE,
new MobileMsgTemplate(
mobile,
contextJson.toJSONString(),
CommonConstant.ALIYUN_SMS,
EnumSmsChannelTemplate.LOGIN_NAME_LOGIN.getSignName(),
EnumSmsChannelTemplate.LOGIN_NAME_LOGIN.getTemplate()
));
redisTemplate.opsForValue().set(SecurityConstants.DEFAULT_CODE_KEY + mobile, code, SecurityConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);
return new R<>(true);
}
複製代碼
public class TreeUtil {
/** * 兩層循環實現建樹 * * @param treeNodes 傳入的樹節點列表 * @return */
public static <T extends TreeNode> List<T> bulid(List<T> treeNodes, Object root) {
List<T> trees = new ArrayList<T>();
for (T treeNode : treeNodes) {
if (root.equals(treeNode.getParentId())) {
trees.add(treeNode);
}
for (T it : treeNodes) {
if (it.getParentId() == treeNode.getId()) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<TreeNode>());
}
treeNode.add(it);
}
}
}
return trees;
}
/** * 使用遞歸方法建樹 * * @param treeNodes * @return */
public static <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, Object root) {
List<T> trees = new ArrayList<T>();
for (T treeNode : treeNodes) {
if (root.equals(treeNode.getParentId())) {
trees.add(findChildren(treeNode, treeNodes));
}
}
return trees;
}
/** * 遞歸查找子節點 * * @param treeNodes * @return */
public static <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
for (T it : treeNodes) {
if (treeNode.getId() == it.getParentId()) {
if (treeNode.getChildren() == null) {
treeNode.setChildren(new ArrayList<TreeNode>());
}
treeNode.add(findChildren(it, treeNodes));
}
}
return treeNode;
}
/** * 經過sysMenu建立樹形節點 * * @param menus * @param root * @return */
public static List<MenuTree> bulidTree(List<SysMenu> menus, int root) {
List<MenuTree> trees = new ArrayList<MenuTree>();
MenuTree node;
for (SysMenu menu : menus) {
node = new MenuTree();
node.setId(menu.getMenuId());
node.setParentId(menu.getParentId());
node.setName(menu.getName());
node.setUrl(menu.getUrl());
node.setPath(menu.getPath());
node.setCode(menu.getPermission());
node.setLabel(menu.getName());
node.setComponent(menu.getComponent());
node.setIcon(menu.getIcon());
trees.add(node);
}
return TreeUtil.bulid(trees, root);
}
}
複製代碼
public class PigResourcesGenerator {
public static void main(String[] args) {
String outputDir = "/Users/lengleng/work/temp";
final String viewOutputDir = outputDir + "/view/";
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(outputDir);
gc.setFileOverride(true);
gc.setActiveRecord(true);
// XML 二級緩存
gc.setEnableCache(false);
// XML ResultMap
gc.setBaseResultMap(true);
// XML columList
gc.setBaseColumnList(true);
gc.setAuthor("lengleng");
mpg.setGlobalConfig(gc);
// 數據源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("lengleng");
dsc.setUrl("jdbc:mysql://139.224.200.249:3309/pig?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false");
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// strategy.setCapitalMode(true);// 全局大寫命名 ORACLE 注意
strategy.setSuperControllerClass("com.github.pig.common.web.BaseController");
// 表名生成策略
strategy.setNaming(NamingStrategy.underline_to_camel);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.github.pig.admin");
pc.setController("controller");
mpg.setPackageInfo(pc);
// 注入自定義配置,能夠在 VM 中使用 cfg.abc 設置的值
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
}
};
// 生成的模版路徑,不存在時須要先新建
File viewDir = new File(viewOutputDir);
if (!viewDir.exists()) {
viewDir.mkdirs();
}
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
focList.add(new FileOutConfig("/templates/listvue.vue.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return getGeneratorViewPath(viewOutputDir, tableInfo, ".vue");
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
//生成controller相關
mpg.execute();
}
/** * 獲取配置文件 * * @return 配置Props */
private static Properties getProperties() {
// 讀取配置文件
Resource resource = new ClassPathResource("/config/application.properties");
Properties props = new Properties();
try {
props = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
/** * 頁面生成的文件名 */
private static String getGeneratorViewPath(String viewOutputDir, TableInfo tableInfo, String suffixPath) {
String name = StringUtils.firstToLowerCase(tableInfo.getEntityName());
String path = viewOutputDir + "/" + name + "/index" + suffixPath;
File viewDir = new File(path).getParentFile();
if (!viewDir.exists()) {
viewDir.mkdirs();
}
return path;
}
}
複製代碼
velocity模板
package $!{package.Controller};
import java.util.Map;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.github.pig.common.constant.CommonConstant;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.common.util.Query;
import com.github.pig.common.util.R;
import $!{package.Entity}.$!{entity};
import $!{package.Service}.$!{entity}Service;
#if($!{superControllerClassPackage})
import $!{superControllerClassPackage};
#end
/**
* <p>
* $!{table.comment} 前端控制器
* </p>
*
* @author $!{author}
* @since $!{date}
*/
@RestController
@RequestMapping("/$!{table.entityPath}")
public class $!{table.controllerName} extends $!{superControllerClass} {
@Autowired private $!{entity}Service $!{table.entityPath}Service;
/**
* 經過ID查詢
*
* @param id ID
* @return $!{entity}
*/
@GetMapping("/{id}")
public R<$!{entity}> get(@PathVariable Integer id) {
return new R<>($!{table.entityPath}Service.selectById(id));
}
/**
* 分頁查詢信息
*
* @param params 分頁對象
* @return 分頁對象
*/
@RequestMapping("/page")
public Page page(@RequestParam Map<String, Object> params) {
params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
return $!{table.entityPath}Service.selectPage(new Query<>(params), new EntityWrapper<>());
}
/**
* 添加
* @param $!{table.entityPath} 實體
* @return success/false
*/
@PostMapping
public R<Boolean> add(@RequestBody $!{entity} $!{table.entityPath}) {
return new R<>($!{table.entityPath}Service.insert($!{table.entityPath}));
}
/**
* 刪除
* @param id ID
* @return success/false
*/
@DeleteMapping("/{id}")
public R<Boolean> delete(@PathVariable Integer id) {
$!{entity} $!{table.entityPath} = new $!{entity}();
$!{table.entityPath}.setId(id);
$!{table.entityPath}.setUpdateTime(new Date());
$!{table.entityPath}.setDelFlag(CommonConstant.STATUS_DEL);
return new R<>($!{table.entityPath}Service.updateById($!{table.entityPath}));
}
/**
* 編輯
* @param $!{table.entityPath} 實體
* @return success/false
*/
@PutMapping
public R<Boolean> edit(@RequestBody $!{entity} $!{table.entityPath}) {
$!{table.entityPath}.setUpdateTime(new Date());
return new R<>($!{table.entityPath}Service.updateById($!{table.entityPath}));
}
}
複製代碼
在部分實現類中,咱們看到了做者使用了spring cache
相關的註解。如今咱們回憶一下相關緩存註解的含義:
@Cacheable
:用來定義緩存的。經常使用到是value,key;分別用來指明緩存的名稱和方法中參數,對於value你也可使用cacheName,在查看源代碼是咱們能夠看到:二者是指的同一個東西。
@CacheEvict
:用來清理緩存。經常使用有cacheNames,allEntries(默認值false);分別表明了要清除的緩存名稱和是否所有清除(true表明所有清除)。
@CachePut
:用來更新緩存,用它來註解的方法都會被執行,執行完後結果被添加到緩存中。該方法不能和@Cacheable同時在同一個方法上使用。
Elastic-Job
是ddframe中dd-job的做業模塊中分離出來的分佈式彈性做業框架。去掉了和dd-job中的監控和ddframe接入規範部分。該項目基於成熟的開源產品Quartz和Zookeeper及其客戶端Curator進行二次開發。主要功能以下:
做者直接使用了開源項目的配置,我順着他的pom文件找到了這家的github,地址以下
@ElasticJobConfig(cron = "0 0 0/1 * * ? ", shardingTotalCount = 3, shardingItemParameters = "0=Beijing,1=Shanghai,2=Guangzhou")
public class PigDataflowJob implements DataflowJob<Integer> {
@Override
public List<Integer> fetchData(ShardingContext shardingContext) {
return null;
}
@Override
public void processData(ShardingContext shardingContext, List<Integer> list) {
}
}
複製代碼
@Slf4j
@ElasticJobConfig(cron = "0 0 0/1 * * ?", shardingTotalCount = 3,
shardingItemParameters = "0=pig1,1=pig2,2=pig3",
startedTimeoutMilliseconds = 5000L,
completedTimeoutMilliseconds = 10000L,
eventTraceRdbDataSource = "dataSource")
public class PigSimpleJob implements SimpleJob {
/** * 業務執行邏輯 * * @param shardingContext 分片信息 */
@Override
public void execute(ShardingContext shardingContext) {
log.info("shardingContext:{}", shardingContext);
}
}
複製代碼
開源版對這個支持有限,等到拿到收費版我在作分析。
這裏的消息中心主要是集成了釘釘服務和阿里大魚短息服務
釘釘是至關簡單了,只須要一個webhook
信息就夠了。
webhook
是一種web回調或者http的push API,是向APP或者其餘應用提供實時信息的一種方式。Webhook在數據產生時當即發送數據,也就是你能實時收到數據。這一種不一樣於典型的API,須要用了實時性須要足夠快的輪詢。這不管是對生產仍是對消費者都是高效的,惟一的缺點是初始創建困難。Webhook有時也被稱爲反向API,由於他提供了API規則,你須要設計要使用的API。Webhook將向你的應用發起http請求,典型的是post請求,應用程序由請求驅動。
@Data
@Configuration
@ConfigurationProperties(prefix = "sms.dingtalk")
public class DingTalkPropertiesConfig {
/** * webhook */
private String webhook;
}
複製代碼
/** * @author lengleng * @date 2018/1/15 * 釘釘消息模板 * msgtype : text * text : {"content":"服務: pig-upms-service 狀態:UP"} */
@Data
@ToString
public class DingTalkMsgTemplate implements Serializable {
private String msgtype;
private TextBean text;
public String getMsgtype() {
return msgtype;
}
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public TextBean getText() {
return text;
}
public void setText(TextBean text) {
this.text = text;
}
public static class TextBean {
/** * content : 服務: pig-upms-service 狀態:UP */
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
}
複製代碼
使用隊列時時監聽
@Slf4j
@Component
@RabbitListener(queues = MqQueueConstant.DINGTALK_SERVICE_STATUS_CHANGE)
public class DingTalkServiceChangeReceiveListener {
@Autowired
private DingTalkMessageHandler dingTalkMessageHandler;
@RabbitHandler
public void receive(String text) {
long startTime = System.currentTimeMillis();
log.info("消息中心接收到釘釘發送請求-> 內容:{} ", text);
dingTalkMessageHandler.process(text);
long useTime = System.currentTimeMillis() - startTime;
log.info("調用 釘釘網關處理完畢,耗時 {}毫秒", useTime);
}
}
複製代碼
使用隊列發送
@Slf4j
@Component
public class DingTalkMessageHandler {
@Autowired
private DingTalkPropertiesConfig dingTalkPropertiesConfig;
/** * 業務處理 * * @param text 消息 */
public boolean process(String text) {
String webhook = dingTalkPropertiesConfig.getWebhook();
if (StrUtil.isBlank(webhook)) {
log.error("釘釘配置錯誤,webhook爲空");
return false;
}
DingTalkMsgTemplate dingTalkMsgTemplate = new DingTalkMsgTemplate();
dingTalkMsgTemplate.setMsgtype("text");
DingTalkMsgTemplate.TextBean textBean = new DingTalkMsgTemplate.TextBean();
textBean.setContent(text);
dingTalkMsgTemplate.setText(textBean);
String result = HttpUtil.post(webhook, JSONObject.toJSONString(dingTalkMsgTemplate));
log.info("釘釘提醒成功,報文響應:{}", result);
return true;
}
}
複製代碼
@Data
@Configuration
@ConditionalOnExpression("!'${sms.aliyun}'.isEmpty()")
@ConfigurationProperties(prefix = "sms.aliyun")
public class SmsAliyunPropertiesConfig {
/** * 應用ID */
private String accessKey;
/** * 應用祕鑰 */
private String secretKey;
/** * 短信模板配置 */
private Map<String, String> channels;
}
複製代碼
@Slf4j
@Component
@RabbitListener(queues = MqQueueConstant.MOBILE_SERVICE_STATUS_CHANGE)
public class MobileServiceChangeReceiveListener {
@Autowired
private Map<String, SmsMessageHandler> messageHandlerMap;
@RabbitHandler
public void receive(MobileMsgTemplate mobileMsgTemplate) {
long startTime = System.currentTimeMillis();
log.info("消息中心接收到短信發送請求-> 手機號:{} -> 信息體:{} ", mobileMsgTemplate.getMobile(), mobileMsgTemplate.getContext());
String channel = mobileMsgTemplate.getChannel();
SmsMessageHandler messageHandler = messageHandlerMap.get(channel);
if (messageHandler == null) {
log.error("沒有找到指定的路由通道,不進行發送處理完畢!");
return;
}
messageHandler.execute(mobileMsgTemplate);
long useTime = System.currentTimeMillis() - startTime;
log.info("調用 {} 短信網關處理完畢,耗時 {}毫秒", mobileMsgTemplate.getType(), useTime);
}
}
複製代碼
不錯的模板
@Slf4j
@Component(CommonConstant.ALIYUN_SMS)
public class SmsAliyunMessageHandler extends AbstractMessageHandler {
@Autowired
private SmsAliyunPropertiesConfig smsAliyunPropertiesConfig;
private static final String PRODUCT = "Dysmsapi";
private static final String DOMAIN = "dysmsapi.aliyuncs.com";
/** * 數據校驗 * * @param mobileMsgTemplate 消息 */
@Override
public void check(MobileMsgTemplate mobileMsgTemplate) {
Assert.isBlank(mobileMsgTemplate.getMobile(), "手機號不能爲空");
Assert.isBlank(mobileMsgTemplate.getContext(), "短信內容不能爲空");
}
/** * 業務處理 * * @param mobileMsgTemplate 消息 */
@Override
public boolean process(MobileMsgTemplate mobileMsgTemplate) {
//可自助調整超時時間
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暫不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsAliyunPropertiesConfig.getAccessKey(), smsAliyunPropertiesConfig.getSecretKey());
try {
DefaultProfile.addEndpoint("cn-hou", "cn-hangzhou", PRODUCT, DOMAIN);
} catch (ClientException e) {
log.error("初始化SDK 異常", e);
e.printStackTrace();
}
IAcsClient acsClient = new DefaultAcsClient(profile);
//組裝請求對象-具體描述見控制檯-文檔部份內容
SendSmsRequest request = new SendSmsRequest();
//必填:待發送手機號
request.setPhoneNumbers(mobileMsgTemplate.getMobile());
//必填:短信簽名-可在短信控制檯中找到
request.setSignName(mobileMsgTemplate.getSignName());
//必填:短信模板-可在短信控制檯中找到
request.setTemplateCode(smsAliyunPropertiesConfig.getChannels().get(mobileMsgTemplate.getTemplate()));
//可選:模板中的變量替換JSON串,如模板內容爲"親愛的${name},您的驗證碼爲${code}"
request.setTemplateParam(mobileMsgTemplate.getContext());
request.setOutId(mobileMsgTemplate.getMobile());
//hint 此處可能會拋出異常,注意catch
try {
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
log.info("短信發送完畢,手機號:{},返回狀態:{}", mobileMsgTemplate.getMobile(), sendSmsResponse.getCode());
} catch (ClientException e) {
log.error("發送異常");
e.printStackTrace();
}
return true;
}
/** * 失敗處理 * * @param mobileMsgTemplate 消息 */
@Override
public void fail(MobileMsgTemplate mobileMsgTemplate) {
log.error("短信發送失敗 -> 網關:{} -> 手機號:{}", mobileMsgTemplate.getType(), mobileMsgTemplate.getMobile());
}
}
複製代碼
因爲做者在認證中心使用了spring security oauth框架,因此須要在微服務的客戶端實現一個資源認證服務器,來完成SSO需求。
暴露監控信息
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.csrf().disable();
}
}
複製代碼
@EnableOAuth2Sso
@SpringBootApplication
public class PigSsoClientDemoApplication {
public static void main(String[] args) {
SpringApplication.run(PigSsoClientDemoApplication.class, args);
}
}
複製代碼
RemindingNotifier
會在應用上線或宕掉的時候發送提醒,也就是把notifications
發送給其餘的notifier
,notifier的實現頗有意思,不深究了,從類關係能夠知道,咱們能夠以這麼幾種方式發送notifications:Pagerduty、Hipchat 、Slack 、Mail、 Reminder
@Configuration
public static class NotifierConfig {
@Bean
@Primary
public RemindingNotifier remindingNotifier() {
RemindingNotifier notifier = new RemindingNotifier(filteringNotifier(loggerNotifier()));
notifier.setReminderPeriod(TimeUnit.SECONDS.toMillis(10));
return notifier;
}
@Scheduled(fixedRate = 1_000L)
public void remind() {
remindingNotifier().sendReminders();
}
@Bean
public FilteringNotifier filteringNotifier(Notifier delegate) {
return new FilteringNotifier(delegate);
}
@Bean
public LoggingNotifier loggerNotifier() {
return new LoggingNotifier();
}
}
複製代碼
繼承AbstractStatusChangeNotifier
,將短信服務註冊到spring boot admin
中。
@Slf4j
public class StatusChangeNotifier extends AbstractStatusChangeNotifier {
private RabbitTemplate rabbitTemplate;
private MonitorPropertiesConfig monitorMobilePropertiesConfig;
public StatusChangeNotifier(MonitorPropertiesConfig monitorMobilePropertiesConfig, RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
this.monitorMobilePropertiesConfig = monitorMobilePropertiesConfig;
}
/** * 通知邏輯 * * @param event 事件 * @throws Exception 異常 */
@Override
protected void doNotify(ClientApplicationEvent event) {
if (event instanceof ClientApplicationStatusChangedEvent) {
log.info("Application {} ({}) is {}", event.getApplication().getName(),
event.getApplication().getId(), ((ClientApplicationStatusChangedEvent) event).getTo().getStatus());
String text = String.format("應用:%s 服務ID:%s 狀態改變爲:%s,時間:%s"
, event.getApplication().getName()
, event.getApplication().getId()
, ((ClientApplicationStatusChangedEvent) event).getTo().getStatus()
, DateUtil.date(event.getTimestamp()).toString());
JSONObject contextJson = new JSONObject();
contextJson.put("name", event.getApplication().getName());
contextJson.put("seid", event.getApplication().getId());
contextJson.put("time", DateUtil.date(event.getTimestamp()).toString());
//開啓短信通知
if (monitorMobilePropertiesConfig.getMobile().getEnabled()) {
log.info("開始短信通知,內容:{}", text);
rabbitTemplate.convertAndSend(MqQueueConstant.MOBILE_SERVICE_STATUS_CHANGE,
new MobileMsgTemplate(
CollUtil.join(monitorMobilePropertiesConfig.getMobile().getMobiles(), ","),
contextJson.toJSONString(),
CommonConstant.ALIYUN_SMS,
EnumSmsChannelTemplate.SERVICE_STATUS_CHANGE.getSignName(),
EnumSmsChannelTemplate.SERVICE_STATUS_CHANGE.getTemplate()
));
}
if (monitorMobilePropertiesConfig.getDingTalk().getEnabled()) {
log.info("開始釘釘通知,內容:{}", text);
rabbitTemplate.convertAndSend(MqQueueConstant.DINGTALK_SERVICE_STATUS_CHANGE, text);
}
} else {
log.info("Application {} ({}) {}", event.getApplication().getName(),
event.getApplication().getId(), event.getType());
}
}
}
複製代碼
因爲zipkin是侵入式,所以這部分組件沒有代碼,只有相關依賴。下面分享一下做者的yaml
server:
port: 5003
# datasoure默認使用JDBC
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: ENC(gc16brBHPNq27HsjaULgKGq00Rz6ZUji)
url: jdbc:mysql://127.0.0.1:3309/pig?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
zipkin:
collector:
rabbitmq:
addresses: 127.0.0.1:5682
password: lengleng
username: pig
queue: zipkin
storage:
type: mysql
複製代碼
server:
port: 5002
zipkin:
collector:
rabbitmq:
addresses: 127.0.0.1:5682
password: lengleng
username: pig
queue: zipkin
storage:
type: elasticsearch
elasticsearch:
hosts: 127.0.0.1:9200
cluster: elasticsearch
index: zipkin
max-requests: 64
index-shards: 5
index-replicas: 1
複製代碼
全片結束,以爲我寫的不錯?想要了解更多精彩新姿式?趕快打開個人👉我的博客 👈吧!
謝謝你那麼可愛,還一直關注着我~❤😝