Commit 740e734e by inrgihc

修正redis缓存问题

parent 2f6de5c1
...@@ -4,5 +4,5 @@ import java.util.Map; ...@@ -4,5 +4,5 @@ import java.util.Map;
public interface CacheFactory { public interface CacheFactory {
<T> Map<String, T> getCacheMap(String key); <T> Map<String, T> getCacheMap(String key, Class<T> clazz);
} }
...@@ -11,7 +11,7 @@ public class HazelcastCacheFactory implements CacheFactory { ...@@ -11,7 +11,7 @@ public class HazelcastCacheFactory implements CacheFactory {
private HazelcastInstance hazelcastInstance; private HazelcastInstance hazelcastInstance;
@Override @Override
public <T> Map<String, T> getCacheMap(String key) { public <T> Map<String, T> getCacheMap(String key, Class<T> clazz) {
return hazelcastInstance.getMap(key); return hazelcastInstance.getMap(key);
} }
......
...@@ -10,7 +10,7 @@ public class RedisCacheFactory implements CacheFactory { ...@@ -10,7 +10,7 @@ public class RedisCacheFactory implements CacheFactory {
private JedisClient jedisClient; private JedisClient jedisClient;
@Override @Override
public <T> Map<String, T> getCacheMap(String key) { public <T> Map<String, T> getCacheMap(String key, Class<T> clazz) {
return new RedisCacheMap<>(key, jedisClient); return new RedisCacheMap<>(key, jedisClient, clazz);
} }
} }
package com.gitee.sqlrest.cache.redis; package com.gitee.sqlrest.cache.redis;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
...@@ -11,11 +10,13 @@ import java.util.Set; ...@@ -11,11 +10,13 @@ import java.util.Set;
public class RedisCacheMap<V> implements Map<String, V> { public class RedisCacheMap<V> implements Map<String, V> {
private final String hashTableKey; private final String hashTableKey;
final private JedisClient jedisClient; private final JedisClient jedisClient;
private final Class<V> valueClazz;
public RedisCacheMap(String hashTableKey, JedisClient jedisClient) { public RedisCacheMap(String hashTableKey, JedisClient jedisClient, Class<V> clazz) {
this.hashTableKey = hashTableKey; this.hashTableKey = hashTableKey;
this.jedisClient = jedisClient; this.jedisClient = jedisClient;
this.valueClazz = clazz;
} }
@Override @Override
...@@ -47,8 +48,7 @@ public class RedisCacheMap<V> implements Map<String, V> { ...@@ -47,8 +48,7 @@ public class RedisCacheMap<V> implements Map<String, V> {
return jedisClient.doAction( return jedisClient.doAction(
jedis -> { jedis -> {
String value = jedis.hget(hashTableKey, o.toString()); String value = jedis.hget(hashTableKey, o.toString());
return JSONUtil.toBean(value, new TypeReference<V>() { return JSONUtil.toBean(value, valueClazz, true);
}, true);
} }
); );
} }
...@@ -59,8 +59,7 @@ public class RedisCacheMap<V> implements Map<String, V> { ...@@ -59,8 +59,7 @@ public class RedisCacheMap<V> implements Map<String, V> {
jedis -> { jedis -> {
String value = jedis.hget(hashTableKey, k); String value = jedis.hget(hashTableKey, k);
jedis.hset(hashTableKey, k, JSONUtil.toJsonStr(v)); jedis.hset(hashTableKey, k, JSONUtil.toJsonStr(v));
return JSONUtil.toBean(value, new TypeReference<V>() { return JSONUtil.toBean(value, valueClazz, true);
}, true);
} }
); );
} }
...@@ -71,8 +70,7 @@ public class RedisCacheMap<V> implements Map<String, V> { ...@@ -71,8 +70,7 @@ public class RedisCacheMap<V> implements Map<String, V> {
jedis -> { jedis -> {
String value = jedis.hget(hashTableKey, o.toString()); String value = jedis.hget(hashTableKey, o.toString());
jedis.hdel(hashTableKey, o.toString()); jedis.hdel(hashTableKey, o.toString());
return JSONUtil.toBean(value, new TypeReference<V>() { return JSONUtil.toBean(value, valueClazz, true);
}, true);
} }
); );
} }
......
...@@ -28,6 +28,6 @@ public class RedisProperties { ...@@ -28,6 +28,6 @@ public class RedisProperties {
private Duration timeout = Duration.ofSeconds(1); private Duration timeout = Duration.ofSeconds(1);
private Duration connectTimeout = Duration.ofSeconds(1); private Duration connectTimeout = Duration.ofSeconds(1);
private String clientName = "sqlrest"; private String clientName = "sqlrest";
private Pool pool; private Pool pool = new Pool();
} }
package com.gitee.sqlrest.common.exception;
public class UnAuthorizedException extends RuntimeException {
public UnAuthorizedException(String message) {
super(message);
}
public UnAuthorizedException(String message, Throwable cause) {
super(message, cause);
}
}
package com.gitee.sqlrest.common.exception;
public class UnPermissionException extends RuntimeException {
public UnPermissionException(String message) {
super(message);
}
public UnPermissionException(String message, Throwable cause) {
super(message, cause);
}
}
...@@ -6,6 +6,8 @@ import com.gitee.sqlrest.common.consts.Constants; ...@@ -6,6 +6,8 @@ import com.gitee.sqlrest.common.consts.Constants;
import com.gitee.sqlrest.common.dto.ResultEntity; import com.gitee.sqlrest.common.dto.ResultEntity;
import com.gitee.sqlrest.common.enums.HttpMethodEnum; import com.gitee.sqlrest.common.enums.HttpMethodEnum;
import com.gitee.sqlrest.common.exception.ResponseErrorCode; import com.gitee.sqlrest.common.exception.ResponseErrorCode;
import com.gitee.sqlrest.common.exception.UnAuthorizedException;
import com.gitee.sqlrest.common.exception.UnPermissionException;
import com.gitee.sqlrest.common.util.TokenUtils; import com.gitee.sqlrest.common.util.TokenUtils;
import com.gitee.sqlrest.core.servlet.ClientTokenService; import com.gitee.sqlrest.core.servlet.ClientTokenService;
import com.gitee.sqlrest.core.util.ServletUtils; import com.gitee.sqlrest.core.util.ServletUtils;
...@@ -89,30 +91,34 @@ public class AuthenticationFilter implements Filter { ...@@ -89,30 +91,34 @@ public class AuthenticationFilter implements Filter {
accessRecordEntity.setClientKey(appKey); accessRecordEntity.setClientKey(appKey);
if (null == appKey) { if (null == appKey) {
log.error("Failed get app key from token [{}].", tokenStr); log.error("Failed get app key from token [{}].", tokenStr);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); throw new UnAuthorizedException("Failed to verify token: " + tokenStr);
String message = String.format("/%s/%s[%s]", Constants.API_PATH_PREFIX, path, method.name());
ResultEntity result = ResultEntity.failed(ResponseErrorCode.ERROR_ACCESS_FORBIDDEN, message);
response.getWriter().append(JSONUtil.toJsonStr(result));
return;
} else { } else {
boolean verify = clientTokenService.verifyAuthGroup(appKey, apiConfigEntity.getGroupId()); boolean verify = clientTokenService.verifyAuthGroup(appKey, apiConfigEntity.getGroupId());
if (!verify) { if (!verify) {
log.error("Failed verify group from token [{}] , app key [{}].", tokenStr, appKey); log.error("Failed verify group from token [{}] , app key [{}].", tokenStr, appKey);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); String message = String.format("/%s/%s[%s]", Constants.API_PATH_PREFIX, path, method.name());
String message = String.format("%s[%s]", path, method.name()); throw new UnPermissionException("No Permission to access: " + message);
ResultEntity result = ResultEntity.failed(ResponseErrorCode.ERROR_ACCESS_FORBIDDEN, message);
response.getWriter().append(JSONUtil.toJsonStr(result));
return;
} }
} }
} }
chain.doFilter(request, response); chain.doFilter(request, response);
} catch (UnAuthorizedException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
accessRecordEntity.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
ResultEntity resultEntity = ResultEntity.failed(ResponseErrorCode.ERROR_ACCESS_FORBIDDEN, e.getMessage());
response.getWriter().append(JSONUtil.toJsonStr(resultEntity));
} catch (UnPermissionException e) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
accessRecordEntity.setStatus(HttpServletResponse.SC_FORBIDDEN);
ResultEntity resultEntity = ResultEntity.failed(ResponseErrorCode.ERROR_ACCESS_FORBIDDEN, e.getMessage());
response.getWriter().append(JSONUtil.toJsonStr(resultEntity));
} catch (Throwable t) { } catch (Throwable t) {
String exception = (null != t.getMessage()) ? t.getMessage() : ExceptionUtil.stacktraceToString(t, 100); String exception = (null != t.getMessage()) ? t.getMessage() : ExceptionUtil.stacktraceToString(t, 100);
accessRecordEntity.setException(exception);
ResultEntity resultEntity = ResultEntity.failed(ResponseErrorCode.ERROR_INTERNAL_ERROR, exception); ResultEntity resultEntity = ResultEntity.failed(ResponseErrorCode.ERROR_INTERNAL_ERROR, exception);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
accessRecordEntity.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().append(JSONUtil.toJsonStr(resultEntity)); response.getWriter().append(JSONUtil.toJsonStr(resultEntity));
accessRecordEntity.setException(exception);
} finally { } finally {
accessRecordEntity.setDuration(System.currentTimeMillis() - accessRecordEntity.getDuration()); accessRecordEntity.setDuration(System.currentTimeMillis() - accessRecordEntity.getDuration());
CompletableFuture.runAsync(() -> accessRecordMapper.insert(accessRecordEntity)); CompletableFuture.runAsync(() -> accessRecordMapper.insert(accessRecordEntity));
......
...@@ -9,6 +9,7 @@ import com.gitee.sqlrest.common.exception.ResponseErrorCode; ...@@ -9,6 +9,7 @@ import com.gitee.sqlrest.common.exception.ResponseErrorCode;
import com.gitee.sqlrest.common.util.TokenUtils; import com.gitee.sqlrest.common.util.TokenUtils;
import com.gitee.sqlrest.persistence.dao.AppClientDao; import com.gitee.sqlrest.persistence.dao.AppClientDao;
import com.gitee.sqlrest.persistence.entity.AppClientEntity; import com.gitee.sqlrest.persistence.entity.AppClientEntity;
import com.gitee.sqlrest.persistence.util.JsonUtils;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Map; import java.util.Map;
import javax.annotation.Resource; import javax.annotation.Resource;
...@@ -32,7 +33,8 @@ public class ClientTokenService { ...@@ -32,7 +33,8 @@ public class ClientTokenService {
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
try { try {
for (AppClientEntity appClient : appClientDao.listAll(null)) { for (AppClientEntity appClient : appClientDao.listAll(null)) {
log.info("Load client app token from persistence :{}", appClient); appClient.setAppSecret("******");
log.info("Load client app token from persistence :{}", JsonUtils.toJsonString(appClient));
if (StringUtils.isNotBlank(appClient.getAccessToken())) { if (StringUtils.isNotBlank(appClient.getAccessToken())) {
AccessToken clientToken = AccessToken.builder() AccessToken clientToken = AccessToken.builder()
.realName(appClient.getName()) .realName(appClient.getName())
...@@ -51,7 +53,8 @@ public class ClientTokenService { ...@@ -51,7 +53,8 @@ public class ClientTokenService {
} }
} }
Map tokenClientMap = cacheFactory.getCacheMap(Constants.CACHE_KEY_TOKEN_CLIENT); Map<String, AccessToken> tokenClientMap = cacheFactory
.getCacheMap(Constants.CACHE_KEY_TOKEN_CLIENT, AccessToken.class);
tokenClientMap.put(appClient.getAccessToken(), clientToken); tokenClientMap.put(appClient.getAccessToken(), clientToken);
} }
} }
...@@ -96,7 +99,8 @@ public class ClientTokenService { ...@@ -96,7 +99,8 @@ public class ClientTokenService {
appClientDao.updateTokenByAppKey(clientId, token); appClientDao.updateTokenByAppKey(clientId, token);
} }
Map tokenClientMap = cacheFactory.getCacheMap(Constants.CACHE_KEY_TOKEN_CLIENT); Map<String, AccessToken> tokenClientMap = cacheFactory
.getCacheMap(Constants.CACHE_KEY_TOKEN_CLIENT, AccessToken.class);
tokenClientMap.put(token, clientToken); tokenClientMap.put(token, clientToken);
return clientToken; return clientToken;
...@@ -107,7 +111,7 @@ public class ClientTokenService { ...@@ -107,7 +111,7 @@ public class ClientTokenService {
return null; return null;
} }
Map<String, AccessToken> tokenClientMap = cacheFactory Map<String, AccessToken> tokenClientMap = cacheFactory
.getCacheMap(Constants.CACHE_KEY_TOKEN_CLIENT); .getCacheMap(Constants.CACHE_KEY_TOKEN_CLIENT, AccessToken.class);
AccessToken clientToken = tokenClientMap.get(tokenStr); AccessToken clientToken = tokenClientMap.get(tokenStr);
if (null == clientToken) { if (null == clientToken) {
return null; return null;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment