pom.xml | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
safePlatfrom-out-web/pom.xml | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/Application.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/exception/GlobalExceptionHandler.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/redis/RedisConfig.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/redis/RedisUtils.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/TokenAuthenticationFilter.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
safePlatfrom-out-web/src/main/resources/config/application-dev.yaml | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 |
pom.xml
@@ -146,6 +146,13 @@ <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatisPlusStarter.version}</version> </dependency> <!-- redis连接 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> safePlatfrom-out-web/pom.xml
@@ -64,4 +64,4 @@ </build> </project> </project> safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/Application.java
@@ -3,6 +3,8 @@ import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; @SpringBootApplication @EnableDubbo safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/exception/GlobalExceptionHandler.java
@@ -38,7 +38,7 @@ @ExceptionHandler(value = BusinessException.class) public ResultVO AHandler(BusinessException e) { logger.warn(e.getMessage()); return new ResultVO(e.getError()); return new ResultVO(e.getCode(),e.getMessage()); } safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/redis/RedisConfig.java
对比新文件 @@ -0,0 +1,43 @@ package com.gkhy.safePlatform.config.redis; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfig { /** * @Description: key和value的序列化方式 */ @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); // json序列化对象 GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // key=>string template.setKeySerializer(stringRedisSerializer); // hash=>string template.setHashKeySerializer(stringRedisSerializer); // value=>json template.setValueSerializer(jackson2JsonRedisSerializer); // hashValue=>json template.setHashValueSerializer(jackson2JsonRedisSerializer); // set template.afterPropertiesSet(); return template; } } safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/redis/RedisUtils.java
对比新文件 @@ -0,0 +1,250 @@ package com.gkhy.safePlatform.config.redis; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.connection.RedisClusterConnection; import org.springframework.data.redis.connection.RedisClusterNode; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.jedis.JedisClusterConnection; import org.springframework.data.redis.connection.jedis.JedisConnection; import org.springframework.data.redis.core.*; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.io.Serializable; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; /** * @Description: redis工具类 */ @Repository("configRedisRepository") @SuppressWarnings(value = { "unchecked", "rawtypes" }) public class RedisUtils { @Resource private RedisTemplate redisTemplate; /** * logger */ private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 写入缓存 * @param key * @param value * @return */ public boolean set(final String key, Object value) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 写入缓存设置时效时间 * @param key * @param value * @return */ public boolean set(final String key, Object value, Long expireTime ,TimeUnit timeUnit) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, timeUnit); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 批量删除对应的value * @param keys */ public void remove(final String... keys) { for (String key : keys) { remove(key); } } /** * 批量删除key * @param pattern */ public void removePattern(final String pattern) { Set<Serializable> keys = redisTemplate.keys(pattern); if (keys.size() > 0){ redisTemplate.delete(keys); } } /** * 删除对应的value * @param key */ public void remove(final String key) { if (exists(key)) { redisTemplate.delete(key); } } /** * 判断缓存中是否有对应的value * @param key * @return */ public boolean exists(final String key) { return redisTemplate.hasKey(key); } /** * 读取缓存 * @param key * @return */ public Object get(final String key) { Object result = null; ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.get(key); return result; } /** * 哈希 添加 * @param key * @param hashKey * @param value */ public void hmSet(String key, Object hashKey, Object value){ HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); hash.put(key,hashKey,value); } /** * 哈希获取数据 * @param key * @param hashKey * @return */ public Object hmGet(String key, Object hashKey){ HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); return hash.get(key,hashKey); } /** * 列表添加 * @param k * @param v */ public void lPush(String k,Object v){ ListOperations<String, Object> list = redisTemplate.opsForList(); list.rightPush(k,v); } /** * 列表获取 * @param k * @param l * @param l1 * @return */ public List<Object> lRange(String k, long l, long l1){ ListOperations<String, Object> list = redisTemplate.opsForList(); return list.range(k,l,l1); } /** * 集合添加 * @param key * @param value */ public void add(String key,Object value){ SetOperations<String, Object> set = redisTemplate.opsForSet(); set.add(key,value); } /** * 集合获取 * @param key * @return */ public Set<Object> setMembers(String key){ SetOperations<String, Object> set = redisTemplate.opsForSet(); return set.members(key); } /** * 有序集合添加 * @param key * @param value * @param scoure */ public void zAdd(String key,Object value,double scoure){ ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); zset.add(key,value,scoure); } /** * 有序集合获取 * @param key * @param scoure * @param scoure1 * @return */ public Set<Object> rangeByScore(String key,double scoure,double scoure1){ ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); return zset.rangeByScore(key, scoure, scoure1); } /** * @Description: 获取过期时间 返回 秒 */ public Long getExpireTime(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * @Description: 重置key 的 过期时间 */ public void resetKeyExpireTime(String key, Long seconds) { redisTemplate.expire(key, seconds, TimeUnit.SECONDS); } public Set<String> scanMatch(String matchKey) { Set<String> keys = new HashSet(); RedisConnectionFactory connectionFactory = redisTemplate.getConnectionFactory(); RedisConnection redisConnection = connectionFactory.getConnection(); Cursor<byte[]> scan = null; if(redisConnection instanceof JedisClusterConnection){ RedisClusterConnection clusterConnection = connectionFactory.getClusterConnection(); Iterable<RedisClusterNode> redisClusterNodes = clusterConnection.clusterGetNodes(); Iterator<RedisClusterNode> iterator = redisClusterNodes.iterator(); while (iterator.hasNext()) { RedisClusterNode next = iterator.next(); scan = clusterConnection.scan(next, ScanOptions.scanOptions().match(matchKey).count(Integer.MAX_VALUE).build()); while (scan.hasNext()) { keys.add(new String(scan.next())); } scan.close(); } return keys; } if(redisConnection instanceof JedisConnection){ scan = redisConnection.scan(ScanOptions.scanOptions().match(matchKey).count(Integer.MAX_VALUE).build()); while (scan.hasNext()){ //找到一次就添加一次 keys.add(new String(scan.next())); } scan.close(); return keys; } return keys; } } safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/TokenAuthenticationFilter.java
@@ -9,6 +9,8 @@ import com.gkhy.safePlatform.commons.enums.RedisKeyEnum; import com.gkhy.safePlatform.commons.enums.ResultCodes; import com.gkhy.safePlatform.commons.exception.BusinessException; import com.gkhy.safePlatform.commons.utils.RPCUtils; import com.gkhy.safePlatform.commons.utils.RedisUtils; import com.gkhy.safePlatform.commons.utils.StringUtils; import com.gkhy.safePlatform.commons.vo.ResultVO; import org.apache.dubbo.config.annotation.DubboReference; @@ -39,6 +41,8 @@ private TokenConfig tokenConfig; @DubboReference(check = false) private AccountAuthService userAccountService; @Autowired private RedisUtils redisUtils; @@ -55,7 +59,7 @@ chain.doFilter(req, resp); } catch (BusinessException e) { // 返回异常 this.writeJSON(req, resp, new ResultVO<>(e.getError())); this.writeJSON(req, resp, new ResultVO<>(e.getCode(),e.getMessage())); } } @@ -75,14 +79,14 @@ // 这里是验证获取权限信息 // 1.从redis中获取对应该用户的权限信息 String accessTokenKey = RedisKeyEnum.authKey(RedisKeyEnum.AUTH_TOKEN, loginUserId); String o = userAccountService.getValueByKeyFromRedis(accessTokenKey); Object o = redisUtils.get(accessTokenKey); // 2.token是否存在 if (o == null) { // 是否存在 throw new BusinessException(ResultCodes.CLIENT_CREDENTIALS_SIGN_INVALID); throw new BusinessException(ResultCodes.CLIENT_CREDENTIALS_TOKEN_INVALID); }else{ Long userId = Long.valueOf(loginUserId); CacheUser cacheUser = JSONObject.parseObject(o, CacheUser.class); CacheUser cacheUser = JSONObject.parseObject(o.toString(), CacheUser.class); assert userId.equals(cacheUser.getUserId()); if ( !authToken.equals(cacheUser.getAccessToken())) { throw new BusinessException(ResultCodes.CLIENT_CREDENTIALS_TOKEN_INVALID); @@ -90,23 +94,51 @@ // 3.redis获取权限 String authoritiesKey = RedisKeyEnum.authKey(RedisKeyEnum.AUTH_AUTHORITIES, userId); String oo = userAccountService.getValueByKeyFromRedis(authoritiesKey); Object oo = redisUtils.get(authoritiesKey); List<GrantedAuthority> authorities = new ArrayList<>(); // 4.redis中是否存在 if (oo != null) { // 5.存在 List<CacheAuthority> cacheAuthorities = JSONArray.parseArray(oo, CacheAuthority.class); List<CacheAuthority> cacheAuthorities = JSONArray.parseArray(oo.toString(), CacheAuthority.class); for (CacheAuthority cacheAuthority: cacheAuthorities) { authorities.add(new SimpleGrantedAuthority(cacheAuthority.getAuthority())); } }else { // 6.不存在=>数据库查询 String roleCode = userAccountService.getUserRoleCodeByUserId(userId); ResultVO<String> rpcResultRole = userAccountService.getUserRoleCodeByUserId(userId); if (rpcResultRole == null) { throw new BusinessException(ResultCodes.RPC_RESULT_NULL); } if (!ResultCodes.OK.getCode().equals(rpcResultRole.getCode())) { throw new BusinessException(rpcResultRole.getCode(), rpcResultRole.getMsg()); } if (rpcResultRole.getData() == null) { throw new BusinessException(ResultCodes.RPC_DATA_NULL); } if (!(rpcResultRole.getData() instanceof String)) { throw new BusinessException(ResultCodes.RPC_DATA_TYPE_NOT_MATCH); } // role authorities.add(new SimpleGrantedAuthority("ROLE_" + roleCode)); authorities.add(new SimpleGrantedAuthority("ROLE_" + rpcResultRole.getData().toString())); // permission List<String> permissions = userAccountService.getUserPermissionByUserId(userId); ResultVO<List<String>> rpcResultPermission = userAccountService.getUserPermissionByUserId(userId); if (rpcResultPermission == null) { throw new BusinessException(ResultCodes.RPC_RESULT_NULL); } if (!ResultCodes.OK.getCode().equals(rpcResultPermission.getCode())) { throw new BusinessException(rpcResultRole.getCode(), rpcResultRole.getMsg()); } if (rpcResultPermission.getData() == null) { throw new BusinessException(ResultCodes.RPC_DATA_NULL); } if (!(rpcResultPermission.getData() instanceof List)) { throw new BusinessException(ResultCodes.RPC_DATA_TYPE_NOT_MATCH); } List<String> permissions = RPCUtils.castList(rpcResultPermission.getData(), String.class); for (String permission : permissions) { SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission); authorities.add(simpleGrantedAuthority); safePlatfrom-out-web/src/main/resources/config/application-dev.yaml
@@ -21,6 +21,19 @@ username: gkhy_dev_out_team password: Adsdf675T6AC7yga type: com.alibaba.druid.pool.DruidDataSource redis: host: 127.0.0.1 port: 6379 password: root # Redis 服务器密码,默认为空。生产中,一定要设置 Redis 密码! database: 0 # Redis 数据库号,默认为 0 timeout: 15000 # Redis 连接超时时间,单位:毫秒。 # 对应 RedisProperties.Jedis 内部类 jedis: pool: max-active: 8 # 连接池最大连接数,默认为 8 。使用负数表示没有限制 同一时间最大只能执行8条sql语句,每执行一条语句就会建立一个连接 max-idle: 8 # 默认连接数最大空闲的连接数,默认为 8 。使用负数表示没有限制。 min-idle: 0 # 默认连接池最小空闲的连接数,默认为 0 。允许设置 0 和 正数。 max-wait: -1 mybatis-plus: