diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/CustomRedisTokenStore.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/CustomRedisTokenStore.java index ffcc6ac6..43193a37 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/CustomRedisTokenStore.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/CustomRedisTokenStore.java @@ -2,7 +2,6 @@ package com.central.oauth2.common.store; import com.central.common.constant.SecurityConstants; import com.central.oauth2.common.properties.SecurityProperties; -import org.springframework.data.redis.connection.RedisClusterConnection; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; @@ -30,8 +29,8 @@ import java.util.List; /** * 优化自Spring Security的RedisTokenStore - * 1. 支持redis cluster模式 - * 2. 非cluster模式时使用pipeline减少连接次数 + * 1. 支持redis所有集群模式包括cluster模式 + * 2. 使用pipeline减少连接次数,提升性能 * 3. 自动续签token(可配置是否开启) * * @author zlt @@ -269,7 +268,7 @@ public class CustomRedisTokenStore implements TokenStore { return; } - this.openPipeline(conn); + conn.openPipeline(); if (springDataRedis_2_0) { try { this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken); @@ -321,7 +320,7 @@ public class CustomRedisTokenStore implements TokenStore { } expireRefreshToken(refreshToken, conn, refreshToAccessKey, accessToRefreshKey); } - this.closePipeline(conn); + conn.closePipeline(); } finally { conn.close(); } @@ -361,14 +360,16 @@ public class CustomRedisTokenStore implements TokenStore { byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue); RedisConnection conn = getConnection(); try { - byte[] access = conn.get(accessKey); - byte[] auth = conn.get(authKey); - this.openPipeline(conn); + conn.openPipeline(); + conn.get(accessKey); + conn.get(authKey); conn.del(accessKey); conn.del(accessToRefreshKey); // Don't remove the refresh token - it's up to the caller to do that conn.del(authKey); - this.closePipeline(conn); + List results = conn.closePipeline(); + byte[] access = (byte[]) results.get(0); + byte[] auth = (byte[]) results.get(1); OAuth2Authentication authentication = deserializeAuthentication(auth); if (authentication != null) { @@ -376,12 +377,12 @@ public class CustomRedisTokenStore implements TokenStore { byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key); byte[] unameKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication)); byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId()); - this.openPipeline(conn); + conn.openPipeline(); conn.del(authToAccessKey); conn.lRem(unameKey, 1, access); conn.lRem(clientId, 1, access); conn.del(serialize(ACCESS + key)); - this.closePipeline(conn); + conn.closePipeline(); } } finally { conn.close(); @@ -395,7 +396,7 @@ public class CustomRedisTokenStore implements TokenStore { byte[] serializedRefreshToken = serialize(refreshToken); RedisConnection conn = getConnection(); try { - this.openPipeline(conn); + conn.openPipeline(); if (springDataRedis_2_0) { try { this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken); @@ -408,7 +409,7 @@ public class CustomRedisTokenStore implements TokenStore { conn.set(refreshAuthKey, serialize(authentication)); } expireRefreshToken(refreshToken, conn, refreshKey, refreshAuthKey); - this.closePipeline(conn); + conn.closePipeline(); } finally { conn.close(); } @@ -452,12 +453,12 @@ public class CustomRedisTokenStore implements TokenStore { byte[] access2RefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue); RedisConnection conn = getConnection(); try { - this.openPipeline(conn); + conn.openPipeline(); conn.del(refreshKey); conn.del(refreshAuthKey); conn.del(refresh2AccessKey); conn.del(access2RefreshKey); - this.closePipeline(conn); + conn.closePipeline(); } finally { conn.close(); } @@ -470,17 +471,20 @@ public class CustomRedisTokenStore implements TokenStore { private void removeAccessTokenUsingRefreshToken(String refreshToken) { byte[] key = serializeKey(REFRESH_TO_ACCESS + refreshToken); - byte[] bytes; + List results = null; RedisConnection conn = getConnection(); try { - bytes = conn.get(key); + conn.openPipeline(); + conn.get(key); conn.del(key); + results = conn.closePipeline(); } finally { conn.close(); } - if (bytes == null) { + if (results == null) { return; } + byte[] bytes = (byte[]) results.get(0); String accessToken = deserializeString(bytes); if (accessToken != null) { removeAccessToken(accessToken); @@ -524,19 +528,4 @@ public class CustomRedisTokenStore implements TokenStore { } return Collections.unmodifiableCollection(accessTokens); } - - private void openPipeline(RedisConnection conn) { - boolean isCluster = conn instanceof RedisClusterConnection; - //cluster集群模式不支持pipeline - if (!isCluster) { - conn.openPipeline(); - } - } - private void closePipeline(RedisConnection conn) { - boolean isCluster = conn instanceof RedisClusterConnection; - //cluster集群模式不支持pipeline - if (!isCluster) { - conn.closePipeline(); - } - } } diff --git a/zlt-commons/zlt-redis-spring-boot-starter/pom.xml b/zlt-commons/zlt-redis-spring-boot-starter/pom.xml index 659e0f72..f069cee8 100644 --- a/zlt-commons/zlt-redis-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-redis-spring-boot-starter/pom.xml @@ -19,27 +19,8 @@ org.springframework.boot spring-boot-starter-data-redis - - - redis.clients - jedis - - - lettuce-core - io.lettuce - - - - - - redis.clients - jedis - - - - org.apache.commons - commons-pool2 + commons-io commons-io diff --git a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedisDistributedLock.java b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedisDistributedLock.java index a663037f..d4c29c3b 100644 --- a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedisDistributedLock.java +++ b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/lock/RedisDistributedLock.java @@ -3,16 +3,15 @@ package com.central.common.redis.lock; import com.central.common.lock.AbstractDistributedLock; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.connection.RedisStringCommands; +import org.springframework.data.redis.connection.ReturnType; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.types.Expiration; import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisCluster; -import java.util.ArrayList; -import java.util.List; import java.util.UUID; +import java.util.concurrent.TimeUnit; /** * redis分布式锁实现 @@ -66,23 +65,15 @@ public class RedisDistributedLock extends AbstractDistributedLock { private boolean setRedis(final String key, final long expire) { try { - String status = redisTemplate.execute((RedisCallback) connection -> { - Object nativeConnection = connection.getNativeConnection(); + boolean status = redisTemplate.execute((RedisCallback) connection -> { String uuid = UUID.randomUUID().toString(); lockFlag.set(uuid); - String result = null; - // 集群模式和单机模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行 - // 集群模式 - if (nativeConnection instanceof JedisCluster) { - result = ((JedisCluster) nativeConnection).set(key, uuid, "NX", "PX", expire); - } - // 单机模式 - else if (nativeConnection instanceof Jedis) { - result = ((Jedis) nativeConnection).set(key, uuid, "NX", "PX", expire); - } + byte[] keyByte = redisTemplate.getStringSerializer().serialize(key); + byte[] uuidByte = redisTemplate.getStringSerializer().serialize(uuid); + boolean result = connection.set(keyByte, uuidByte, Expiration.from(expire, TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.ifAbsent()); return result; }); - return !StringUtils.isEmpty(status); + return status; } catch (Exception e) { log.error("set redisDistributeLock occured an exception", e); } @@ -93,30 +84,15 @@ public class RedisDistributedLock extends AbstractDistributedLock { public boolean releaseLock(String key) { // 释放锁的时候,有可能因为持锁之后方法执行时间大于锁的有效期,此时有可能已经被另外一个线程持有锁,所以不能直接删除 try { - final List keys = new ArrayList<>(); - keys.add(key); - final List args = new ArrayList<>(); - args.add(lockFlag.get()); - // 使用lua脚本删除redis中匹配value的key,可以避免由于方法执行时间过长而redis锁自动过期失效的时候误删其他线程的锁 // spring自带的执行脚本方法中,集群模式直接抛出不支持执行脚本的异常,所以只能拿到原redis的connection来执行脚本 - - Long result = redisTemplate.execute((RedisCallback) connection -> { - Object nativeConnection = connection.getNativeConnection(); - // 集群模式和单机模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行 - // 集群模式 - if (nativeConnection instanceof JedisCluster) { - return (Long) ((JedisCluster) nativeConnection).eval(UNLOCK_LUA, keys, args); - } - - // 单机模式 - else if (nativeConnection instanceof Jedis) { - return (Long) ((Jedis) nativeConnection).eval(UNLOCK_LUA, keys, args); - } - return 0L; + Boolean result = redisTemplate.execute((RedisCallback) connection -> { + byte[] scriptByte = redisTemplate.getStringSerializer().serialize(UNLOCK_LUA); + return connection.eval(scriptByte, ReturnType.BOOLEAN, 1 + , redisTemplate.getStringSerializer().serialize(key) + , redisTemplate.getStringSerializer().serialize(lockFlag.get())); }); - - return result != null && result > 0; + return result; } catch (Exception e) { log.error("release redisDistributeLock occured an exception", e); } finally { diff --git a/zlt-config/src/main/resources/application.properties b/zlt-config/src/main/resources/application.properties index 3aa0ec45..f40e8145 100644 --- a/zlt-config/src/main/resources/application.properties +++ b/zlt-config/src/main/resources/application.properties @@ -83,17 +83,6 @@ spring.datasource.druid.stat-view-servlet.login-username=admin spring.datasource.druid.stat-view-servlet.login-password=admin -##### redis-jedis连接池配置 -#最大等待时间 -spring.redis.jedis.pool.max-wait=1000ms -#最小空闲数量 -spring.redis.jedis.pool.min-idle=50 -#最大空闲数量 -spring.redis.jedis.pool.max-idle=50 -#最大连接数量 -spring.redis.jedis.pool.max-active=1000 - - ##### mybatis-plus配置 #字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断" mybatis-plus.global-config.db-config.field-strategy=NOT_NULL diff --git a/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutHandler.java b/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutHandler.java index f15a7ceb..575b6a29 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutHandler.java +++ b/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutHandler.java @@ -1,5 +1,6 @@ package com.central.oauth.handler; +import cn.hutool.core.util.StrUtil; import com.central.oauth2.common.util.AuthUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -26,8 +27,11 @@ public class OauthLogoutHandler implements LogoutHandler { @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { Assert.notNull(tokenStore, "tokenStore must be set"); - String token = AuthUtils.extractToken(request); - if(StringUtils.isNotBlank(token)){ + String token = request.getParameter("token"); + if (StrUtil.isEmpty(token)) { + token = AuthUtils.extractToken(request); + } + if(StrUtil.isNotEmpty(token)){ OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token); OAuth2RefreshToken refreshToken; if (existingAccessToken != null) { diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java index 2bcad51f..8916a24e 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisTokensServiceImpl.java @@ -52,7 +52,9 @@ public class RedisTokensServiceImpl implements ITokensService { tokenVo.setClientId(clientId); tokenVo.setTokenValue(accessToken.getValue()); tokenVo.setExpiration(accessToken.getExpiration()); - tokenVo.setUsername(authentication.getName()); + if (authentication != null) { + tokenVo.setUsername(authentication.getName()); + } result.add(tokenVo); } } diff --git a/zlt-web/back-web/src/main/resources/static/pages/system/tokens.html b/zlt-web/back-web/src/main/resources/static/pages/system/tokens.html index b02d855d..17ba768c 100644 --- a/zlt-web/back-web/src/main/resources/static/pages/system/tokens.html +++ b/zlt-web/back-web/src/main/resources/static/pages/system/tokens.html @@ -63,11 +63,11 @@ layer.confirm('确定要删除吗?', function (i) { layer.close(i); layer.load(2); - admin.req('api-uaa/oauth/remove/token?access_token=' + obj.data.tokenValue, {}, function (data) { + admin.req('api-uaa/oauth/remove/token?token=' + obj.data.tokenValue, {}, function (data) { layer.closeAll('loading'); layer.msg('成功', {icon: 1, time: 500}); obj.del(); - }, 'DELETE', true); + }, 'DELETE'); }); };