redis客户端使用lettuce代替jedis

This commit is contained in:
zlt
2019-07-12 15:44:57 +08:00
parent 482bc3d9b7
commit 426f0b6ac1
7 changed files with 49 additions and 108 deletions
@@ -2,7 +2,6 @@ package com.central.oauth2.common.store;
import com.central.common.constant.SecurityConstants; import com.central.common.constant.SecurityConstants;
import com.central.oauth2.common.properties.SecurityProperties; 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.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
@@ -30,8 +29,8 @@ import java.util.List;
/** /**
* 优化自Spring Security的RedisTokenStore * 优化自Spring Security的RedisTokenStore
* 1. 支持redis cluster模式 * 1. 支持redis所有集群模式包括cluster模式
* 2. 非cluster模式时使用pipeline减少连接次数 * 2. 使用pipeline减少连接次数,提升性能
* 3. 自动续签token(可配置是否开启) * 3. 自动续签token(可配置是否开启)
* *
* @author zlt * @author zlt
@@ -269,7 +268,7 @@ public class CustomRedisTokenStore implements TokenStore {
return; return;
} }
this.openPipeline(conn); conn.openPipeline();
if (springDataRedis_2_0) { if (springDataRedis_2_0) {
try { try {
this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken); this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken);
@@ -321,7 +320,7 @@ public class CustomRedisTokenStore implements TokenStore {
} }
expireRefreshToken(refreshToken, conn, refreshToAccessKey, accessToRefreshKey); expireRefreshToken(refreshToken, conn, refreshToAccessKey, accessToRefreshKey);
} }
this.closePipeline(conn); conn.closePipeline();
} finally { } finally {
conn.close(); conn.close();
} }
@@ -361,14 +360,16 @@ public class CustomRedisTokenStore implements TokenStore {
byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue); byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
RedisConnection conn = getConnection(); RedisConnection conn = getConnection();
try { try {
byte[] access = conn.get(accessKey); conn.openPipeline();
byte[] auth = conn.get(authKey); conn.get(accessKey);
this.openPipeline(conn); conn.get(authKey);
conn.del(accessKey); conn.del(accessKey);
conn.del(accessToRefreshKey); conn.del(accessToRefreshKey);
// Don't remove the refresh token - it's up to the caller to do that // Don't remove the refresh token - it's up to the caller to do that
conn.del(authKey); conn.del(authKey);
this.closePipeline(conn); List<Object> results = conn.closePipeline();
byte[] access = (byte[]) results.get(0);
byte[] auth = (byte[]) results.get(1);
OAuth2Authentication authentication = deserializeAuthentication(auth); OAuth2Authentication authentication = deserializeAuthentication(auth);
if (authentication != null) { if (authentication != null) {
@@ -376,12 +377,12 @@ public class CustomRedisTokenStore implements TokenStore {
byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key); byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key);
byte[] unameKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication)); byte[] unameKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication));
byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId()); byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
this.openPipeline(conn); conn.openPipeline();
conn.del(authToAccessKey); conn.del(authToAccessKey);
conn.lRem(unameKey, 1, access); conn.lRem(unameKey, 1, access);
conn.lRem(clientId, 1, access); conn.lRem(clientId, 1, access);
conn.del(serialize(ACCESS + key)); conn.del(serialize(ACCESS + key));
this.closePipeline(conn); conn.closePipeline();
} }
} finally { } finally {
conn.close(); conn.close();
@@ -395,7 +396,7 @@ public class CustomRedisTokenStore implements TokenStore {
byte[] serializedRefreshToken = serialize(refreshToken); byte[] serializedRefreshToken = serialize(refreshToken);
RedisConnection conn = getConnection(); RedisConnection conn = getConnection();
try { try {
this.openPipeline(conn); conn.openPipeline();
if (springDataRedis_2_0) { if (springDataRedis_2_0) {
try { try {
this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken); this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken);
@@ -408,7 +409,7 @@ public class CustomRedisTokenStore implements TokenStore {
conn.set(refreshAuthKey, serialize(authentication)); conn.set(refreshAuthKey, serialize(authentication));
} }
expireRefreshToken(refreshToken, conn, refreshKey, refreshAuthKey); expireRefreshToken(refreshToken, conn, refreshKey, refreshAuthKey);
this.closePipeline(conn); conn.closePipeline();
} finally { } finally {
conn.close(); conn.close();
} }
@@ -452,12 +453,12 @@ public class CustomRedisTokenStore implements TokenStore {
byte[] access2RefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue); byte[] access2RefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
RedisConnection conn = getConnection(); RedisConnection conn = getConnection();
try { try {
this.openPipeline(conn); conn.openPipeline();
conn.del(refreshKey); conn.del(refreshKey);
conn.del(refreshAuthKey); conn.del(refreshAuthKey);
conn.del(refresh2AccessKey); conn.del(refresh2AccessKey);
conn.del(access2RefreshKey); conn.del(access2RefreshKey);
this.closePipeline(conn); conn.closePipeline();
} finally { } finally {
conn.close(); conn.close();
} }
@@ -470,17 +471,20 @@ public class CustomRedisTokenStore implements TokenStore {
private void removeAccessTokenUsingRefreshToken(String refreshToken) { private void removeAccessTokenUsingRefreshToken(String refreshToken) {
byte[] key = serializeKey(REFRESH_TO_ACCESS + refreshToken); byte[] key = serializeKey(REFRESH_TO_ACCESS + refreshToken);
byte[] bytes; List<Object> results = null;
RedisConnection conn = getConnection(); RedisConnection conn = getConnection();
try { try {
bytes = conn.get(key); conn.openPipeline();
conn.get(key);
conn.del(key); conn.del(key);
results = conn.closePipeline();
} finally { } finally {
conn.close(); conn.close();
} }
if (bytes == null) { if (results == null) {
return; return;
} }
byte[] bytes = (byte[]) results.get(0);
String accessToken = deserializeString(bytes); String accessToken = deserializeString(bytes);
if (accessToken != null) { if (accessToken != null) {
removeAccessToken(accessToken); removeAccessToken(accessToken);
@@ -524,19 +528,4 @@ public class CustomRedisTokenStore implements TokenStore {
} }
return Collections.unmodifiableCollection(accessTokens); 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();
}
}
} }
@@ -19,27 +19,8 @@
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId> <artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</exclusion>
<exclusion>
<artifactId>lettuce-core</artifactId>
<groupId>io.lettuce</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- jedis客户端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- spring2.X集成redis所需common-pool2,使用jedis必须依赖它-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
@@ -3,16 +3,15 @@ package com.central.common.redis.lock;
import com.central.common.lock.AbstractDistributedLock; import com.central.common.lock.AbstractDistributedLock;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; 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.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Component; 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.UUID;
import java.util.concurrent.TimeUnit;
/** /**
* redis分布式锁实现 * redis分布式锁实现
@@ -66,23 +65,15 @@ public class RedisDistributedLock extends AbstractDistributedLock {
private boolean setRedis(final String key, final long expire) { private boolean setRedis(final String key, final long expire) {
try { try {
String status = redisTemplate.execute((RedisCallback<String>) connection -> { boolean status = redisTemplate.execute((RedisCallback<Boolean>) connection -> {
Object nativeConnection = connection.getNativeConnection();
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
lockFlag.set(uuid); lockFlag.set(uuid);
String result = null; 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());
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);
}
return result; return result;
}); });
return !StringUtils.isEmpty(status); return status;
} catch (Exception e) { } catch (Exception e) {
log.error("set redisDistributeLock occured an exception", e); log.error("set redisDistributeLock occured an exception", e);
} }
@@ -93,30 +84,15 @@ public class RedisDistributedLock extends AbstractDistributedLock {
public boolean releaseLock(String key) { public boolean releaseLock(String key) {
// 释放锁的时候,有可能因为持锁之后方法执行时间大于锁的有效期,此时有可能已经被另外一个线程持有锁,所以不能直接删除 // 释放锁的时候,有可能因为持锁之后方法执行时间大于锁的有效期,此时有可能已经被另外一个线程持有锁,所以不能直接删除
try { try {
final List<String> keys = new ArrayList<>();
keys.add(key);
final List<String> args = new ArrayList<>();
args.add(lockFlag.get());
// 使用lua脚本删除redis中匹配value的key,可以避免由于方法执行时间过长而redis锁自动过期失效的时候误删其他线程的锁 // 使用lua脚本删除redis中匹配value的key,可以避免由于方法执行时间过长而redis锁自动过期失效的时候误删其他线程的锁
// spring自带的执行脚本方法中,集群模式直接抛出不支持执行脚本的异常,所以只能拿到原redis的connection来执行脚本 // spring自带的执行脚本方法中,集群模式直接抛出不支持执行脚本的异常,所以只能拿到原redis的connection来执行脚本
Boolean result = redisTemplate.execute((RedisCallback<Boolean>) connection -> {
Long result = redisTemplate.execute((RedisCallback<Long>) connection -> { byte[] scriptByte = redisTemplate.getStringSerializer().serialize(UNLOCK_LUA);
Object nativeConnection = connection.getNativeConnection(); return connection.eval(scriptByte, ReturnType.BOOLEAN, 1
// 集群模式和单机模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行 , redisTemplate.getStringSerializer().serialize(key)
// 集群模式 , redisTemplate.getStringSerializer().serialize(lockFlag.get()));
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;
}); });
return result;
return result != null && result > 0;
} catch (Exception e) { } catch (Exception e) {
log.error("release redisDistributeLock occured an exception", e); log.error("release redisDistributeLock occured an exception", e);
} finally { } finally {
@@ -83,17 +83,6 @@ spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=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配置 ##### mybatis-plus配置
#字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断" #字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断"
mybatis-plus.global-config.db-config.field-strategy=NOT_NULL mybatis-plus.global-config.db-config.field-strategy=NOT_NULL
@@ -1,5 +1,6 @@
package com.central.oauth.handler; package com.central.oauth.handler;
import cn.hutool.core.util.StrUtil;
import com.central.oauth2.common.util.AuthUtils; import com.central.oauth2.common.util.AuthUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@@ -26,8 +27,11 @@ public class OauthLogoutHandler implements LogoutHandler {
@Override @Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
Assert.notNull(tokenStore, "tokenStore must be set"); Assert.notNull(tokenStore, "tokenStore must be set");
String token = AuthUtils.extractToken(request); String token = request.getParameter("token");
if(StringUtils.isNotBlank(token)){ if (StrUtil.isEmpty(token)) {
token = AuthUtils.extractToken(request);
}
if(StrUtil.isNotEmpty(token)){
OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token); OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
OAuth2RefreshToken refreshToken; OAuth2RefreshToken refreshToken;
if (existingAccessToken != null) { if (existingAccessToken != null) {
@@ -52,7 +52,9 @@ public class RedisTokensServiceImpl implements ITokensService {
tokenVo.setClientId(clientId); tokenVo.setClientId(clientId);
tokenVo.setTokenValue(accessToken.getValue()); tokenVo.setTokenValue(accessToken.getValue());
tokenVo.setExpiration(accessToken.getExpiration()); tokenVo.setExpiration(accessToken.getExpiration());
tokenVo.setUsername(authentication.getName()); if (authentication != null) {
tokenVo.setUsername(authentication.getName());
}
result.add(tokenVo); result.add(tokenVo);
} }
} }
@@ -63,11 +63,11 @@
layer.confirm('确定要删除吗?', function (i) { layer.confirm('确定要删除吗?', function (i) {
layer.close(i); layer.close(i);
layer.load(2); 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.closeAll('loading');
layer.msg('成功', {icon: 1, time: 500}); layer.msg('成功', {icon: 1, time: 500});
obj.del(); obj.del();
}, 'DELETE', true); }, 'DELETE');
}); });
}; };