配置A:
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.ZSetOperations;
public interface IRedisCommand<K, V> {
Long getExpire(String paramString);
double getCreateTimeScore(long paramLong);
Set<K> getAllKeys();
Map<K, V> getAllString();
Map<K, Set<V>> getAllSet();
Map<K, Set<V>> getAllZSetReverseRange();
Map<K, Set<V>> getAllZSetRange();
Map<K, List<V>> getAllList();
Map<K, Map<K, V>> getAllMap();
void addList(K paramK, List<V> paramList);
long addList(K paramK, V paramV);
long addList(K paramK, V... paramVarArgs);
List<V> getList(K paramK, long paramLong1, long paramLong2);
List<V> getList(K paramK);
long getListSize(K paramK);
long removeListValue(K paramK, V paramV);
long removeListValue(K paramK, V... paramVarArgs);
void remove(K... paramVarArgs);
void remove(K paramK);
void removeZSetRangeByScore(String paramString, double paramDouble1, double paramDouble2);
Boolean setSetExpireTime(String paramString, Long paramLong);
Boolean setZSetExpireTime(String paramString, Long paramLong);
boolean exists(K paramK);
void delKey(String paramString);
V get(K paramK);
List<V> get(K... paramVarArgs);
List<Object> getByRegular(K paramK);
void set(K paramK, V paramV);
void set(K paramK, V paramV, Long paramLong);
boolean setExpireTime(K paramK, Long paramLong);
DataType getType(K paramK);
void removeMapField(K paramK, V... paramVarArgs);
Map<K, V> getMap(K paramK);
Long getMapSize(K paramK);
<T> T getMapField(K paramK1, K paramK2);
Boolean hasMapKey(K paramK1, K paramK2);
List<V> getMapFieldValue(K paramK);
Set<V> getMapFieldKey(K paramK);
void addMap(K paramK, Map<K, V> paramMap);
void addMap(K paramK1, K paramK2, Object paramObject);
void addMap(K paramK1, K paramK2, V paramV, long paramLong);
void addSet(K paramK, V... paramVarArgs);
void watch(String paramString);
long removeSetValue(K paramK, V paramV);
long removeSetValue(K paramK, V... paramVarArgs);
long getSetSize(K paramK);
Boolean hasSetValue(K paramK, V paramV);
Set<V> getSet(K paramK);
Set<V> getSetUnion(K paramK1, K paramK2);
Set<V> getSetUnion(K paramK, Set<Object> paramSet);
Set<V> getSetIntersect(K paramK1, K paramK2);
Set<V> getSetIntersect(K paramK, Set<Object> paramSet);
void removeBlear(K... paramVarArgs);
Boolean renameIfAbsent(String paramString1, String paramString2);
void removeBlear(K paramK);
void removeByRegular(String... paramVarArgs);
void removeByRegular(String paramString);
void removeMapFieldByRegular(K paramK, K... paramVarArgs);
void removeMapFieldByRegular(K paramK1, K paramK2);
Long removeZSetValue(K paramK, V... paramVarArgs);
void removeZSet(K paramK);
void removeZSetRange(K paramK, Long paramLong1, Long paramLong2);
void setZSetUnionAndStore(String paramString1, String paramString2, String paramString3);
<T> T getZSetRange(K paramK);
<T> T getZSetRange(K paramK, long paramLong1, long paramLong2);
Set<Object> getZSetReverseRange(K paramK);
Set<V> getZSetReverseRange(K paramK, long paramLong1, long paramLong2);
Set<V> getZSetRangeByScore(String paramString, double paramDouble1, double paramDouble2);
Set<V> getZSetReverseRangeByScore(String paramString, double paramDouble1, double paramDouble2);
Set<ZSetOperations.TypedTuple<V>> getZSetRangeWithScores(K paramK, long paramLong1, long paramLong2);
Set<ZSetOperations.TypedTuple<V>> getZSetReverseRangeWithScores(K paramK, long paramLong1, long paramLong2);
Set<ZSetOperations.TypedTuple<V>> getZSetRangeWithScores(K paramK);
Set<ZSetOperations.TypedTuple<V>> getZSetReverseRangeWithScores(K paramK);
long getZSetCountSize(K paramK, double paramDouble1, double paramDouble2);
long getZSetSize(K paramK);
double getZSetScore(K paramK, V paramV);
double incrementZSetScore(K paramK, V paramV, double paramDouble);
Boolean addZSet(String paramString, double paramDouble, Object paramObject);
Long addZSet(K paramK, TreeSet<V> paramTreeSet);
Boolean addZSet(K paramK, double[] paramArrayOfdouble, Object[] paramArrayOfObject);
}
/* */ import java.util.ArrayList;
/* */ import java.util.HashMap;
/* */ import java.util.Iterator;
/* */ import java.util.List;
/* */ import java.util.Map;
/* */ import java.util.Set;
/* */ import java.util.TreeSet;
/* */ import java.util.concurrent.TimeUnit;
/* */ import java.util.regex.Pattern;
/* */ import org.apache.log4j.Logger;
/* */ import org.springframework.data.redis.connection.DataType;
/* */ import org.springframework.data.redis.core.RedisTemplate;
/* */ import org.springframework.data.redis.core.ZSetOperations;
/* */ import org.springframework.util.CollectionUtils;
/* */
/* */ @Component
/* */ public class RedisCommand implements IRedisCommand<String, Object> {
/* 19 */ private Logger logger = Logger.getLogger(RedisCommand.class);
/* */
/* */
/* */ @Autowired
/* */ @Qualifier("RedisTemplateUtils")
/* */ protected RedisTemplate redisTemplate;
/* */
/* */
/* 27 */ private static Integer times = Integer.valueOf(5);
/* */
/* */
/* */ public Long getExpire(String key) {
/* 31 */ return this.redisTemplate.getExpire(key);
/* */ }
/* */
/* */
/* */ public double getCreateTimeScore(long date) {
/* 36 */ return date / 100000.0D;
/* */ }
/* */
/* */
/* */ public Set<String> getAllKeys() {
/* 41 */ return this.redisTemplate.keys("*");
/* */ }
/* */
/* */
/* */
/* */ public Map<String, Object> getAllString() {
/* 47 */ Set<String> stringSet = getAllKeys();
/* 48 */ Map<String, Object> map = new HashMap<>();
/* 49 */ Iterator<String> iterator = stringSet.iterator();
/* 50 */ while (iterator.hasNext()) {
/* 51 */ String k = iterator.next();
/* 52 */ if (getType(k) == DataType.STRING) {
/* 53 */ map.put(k, get(k));
/* */ }
/* */ }
/* 56 */ return map;
/* */ }
/* */
/* */
/* */ public Map<String, Set<Object>> getAllSet() {
/* 61 */ Set<String> stringSet = getAllKeys();
/* 62 */ Map<String, Set<Object>> map = new HashMap<>();
/* 63 */ Iterator<String> iterator = stringSet.iterator();
/* 64 */ while (iterator.hasNext()) {
/* 65 */ String k = iterator.next();
/* 66 */ if (getType(k) == DataType.SET) {
/* 67 */ map.put(k, getSet(k));
/* */ }
/* */ }
/* 70 */ return map;
/* */ }
/* */
/* */
/* */ public Map<String, Set<Object>> getAllZSetRange() {
/* 75 */ Set<String> stringSet = getAllKeys();
/* 76 */ Map<String, Set<Object>> map = new HashMap<>();
/* 77 */ Iterator<String> iterator = stringSet.iterator();
/* 78 */ while (iterator.hasNext()) {
/* 79 */ String k = iterator.next();
/* 80 */ if (getType(k) == DataType.ZSET) {
/* 81 */ this.logger.debug("k:" + k);
/* 82 */ map.put(k, getZSetRange(k));
/* */ }
/* */ }
/* 85 */ return map;
/* */ }
/* */
/* */
/* */ public Map<String, Set<Object>> getAllZSetReverseRange() {
/* 90 */ Set<String> stringSet = getAllKeys();
/* 91 */ Map<String, Set<Object>> map = new HashMap<>();
/* 92 */ Iterator<String> iterator = stringSet.iterator();
/* 93 */ while (iterator.hasNext()) {
/* 94 */ String k = iterator.next();
/* 95 */ if (getType(k) == DataType.ZSET) {
/* 96 */ map.put(k, getZSetReverseRange(k));
/* */ }
/* */ }
/* 99 */ return map;
/* */ }
/* */
/* */
/* */ public Map<String, List<Object>> getAllList() {
/* 104 */ Set<String> stringSet = getAllKeys();
/* 105 */ Map<String, List<Object>> map = new HashMap<>();
/* 106 */ Iterator<String> iterator = stringSet.iterator();
/* 107 */ while (iterator.hasNext()) {
/* 108 */ String k = iterator.next();
/* 109 */ if (getType(k) == DataType.LIST) {
/* 110 */ map.put(k, getList(k));
/* */ }
/* */ }
/* 113 */ return map;
/* */ }
/* */
/* */
/* */ public Map<String, Map<String, Object>> getAllMap() {
/* 118 */ Set<String> stringSet = getAllKeys();
/* 119 */ Map<String, Map<String, Object>> map = new HashMap<>();
/* 120 */ Iterator<String> iterator = stringSet.iterator();
/* 121 */ while (iterator.hasNext()) {
/* 122 */ String k = iterator.next();
/* 123 */ if (getType(k) == DataType.HASH) {
/* 124 */ map.put(k, getMap(k));
/* */ }
/* */ }
/* 127 */ return map;
/* */ }
/* */
/* */
/* */ public void addList(String key, List<Object> objectList) {
/* 132 */ for (Object obj : objectList) {
/* 133 */ addList(key, obj);
/* */ }
/* */ }
/* */
/* */
/* */ public long addList(String key, Object obj) {
/* 139 */ return this.redisTemplate.boundListOps(key).rightPush(obj).longValue();
/* */ }
/* */
/* */
/* */ public long addList(String key, Object... obj) {
/* 144 */ return this.redisTemplate.boundListOps(key).rightPushAll(obj).longValue();
/* */ }
/* */
/* */
/* */ public List<Object> getList(String key, long s, long e) {
/* 149 */ return this.redisTemplate.boundListOps(key).range(s, e);
/* */ }
/* */
/* */
/* */ public List<Object> getList(String key) {
/* 154 */ return this.redisTemplate.boundListOps(key).range(0L, getListSize(key));
/* */ }
/* */
/* */
/* */ public long getListSize(String key) {
/* 159 */ return this.redisTemplate.boundListOps(key).size().longValue();
/* */ }
/* */
/* */
/* */ public long removeListValue(String key, Object object) {
/* 164 */ return this.redisTemplate.boundListOps(key).remove(0L, object).longValue();
/* */ }
/* */
/* */
/* */ public long removeListValue(String key, Object... objects) {
/* 169 */ long r = 0L;
/* 170 */ for (Object object : objects) {
/* 171 */ r += removeListValue(key, object);
/* */ }
/* 173 */ return r;
/* */ }
/* */
/* */
/* */ public void remove(String... key) {
/* 178 */ if (key != null && key.length > 0) {
/* 179 */ if (key.length == 1) {
/* 180 */ remove(key[0]);
/* */ } else {
/* 182 */ this.redisTemplate.delete(CollectionUtils.arrayToList(key));
/* */ }
/* */ }
/* */ }
/* */
/* */
/* */ public void removeBlear(String... blears) {
/* 189 */ for (String blear : blears) {
/* 190 */ removeBlear(blear);
/* */ }
/* */ }
/* */
/* */
/* */ public Boolean renameIfAbsent(String oldKey, String newKey) {
/* 196 */ return this.redisTemplate.renameIfAbsent(oldKey, newKey);
/* */ }
/* */
/* */
/* */ public void removeBlear(String blear) {
/* 201 */ this.redisTemplate.delete(this.redisTemplate.keys(blear));
/* */ }
/* */
/* */
/* */ public void removeByRegular(String... blears) {
/* 206 */ for (String blear : blears) {
/* 207 */ removeBlear(blear);
/* */ }
/* */ }
/* */
/* */
/* */ public void removeByRegular(String blear) {
/* 213 */ Set<String> stringSet = getAllKeys();
/* 214 */ for (String s : stringSet) {
/* 215 */ if (Pattern.compile(blear).matcher(s).matches()) {
/* 216 */ this.redisTemplate.delete(s);
/* */ }
/* */ }
/* */ }
/* */
/* */
/* */ public void removeMapFieldByRegular(String key, String... blears) {
/* 223 */ for (String blear : blears) {
/* 224 */ removeMapFieldByRegular(key, blear);
/* */ }
/* */ }
/* */
/* */
/* */ public void removeMapFieldByRegular(String key, String blear) {
/* 230 */ Map<String, Object> map = getMap(key);
/* 231 */ Set<String> stringSet = map.keySet();
/* 232 */ for (String s : stringSet) {
/* 233 */ if (Pattern.compile(blear).matcher(s).matches()) {
/* 234 */ this.redisTemplate.boundHashOps(key).delete(new Object[] { s });
/* */ }
/* */ }
/* */ }
/* */
/* */
/* */ public Long removeZSetValue(String key, Object... value) {
/* 241 */ return this.redisTemplate.boundZSetOps(key).remove(value);
/* */ }
/* */
/* */
/* */ public void removeZSet(String key) {
/* 246 */ removeZSetRange(key, Long.valueOf(0L), Long.valueOf(getZSetSize(key)));
/* */ }
/* */
/* */
/* */ public void removeZSetRange(String key, Long start, Long end) {
/* 251 */ this.redisTemplate.boundZSetOps(key).removeRange(start.longValue(), end.longValue());
/* */ }
/* */
/* */
/* */ public void setZSetUnionAndStore(String key, String key1, String key2) {
/* 256 */ this.redisTemplate.boundZSetOps(key).unionAndStore(key1, key2);
/* */ }
/* */
/* */
/* */ public Set<Object> getZSetRange(String key) {
/* 261 */ return getZSetRange(key, 0L, getZSetSize(key));
/* */ }
/* */
/* */
/* */ public Set<Object> getZSetRange(String key, long s, long e) {
/* 266 */ return this.redisTemplate.boundZSetOps(key).range(s, e);
/* */ }
/* */
/* */
/* */ public Set<Object> getZSetReverseRange(String key) {
/* 271 */ return getZSetReverseRange(key, 0L, getZSetSize(key));
/* */ }
/* */
/* */
/* */ public Set<Object> getZSetReverseRange(String key, long start, long end) {
/* 276 */ return this.redisTemplate.boundZSetOps(key).reverseRange(start, end);
/* */ }
/* */
/* */
/* */ public Set<Object> getZSetRangeByScore(String key, double start, double end) {
/* 281 */ return this.redisTemplate.boundZSetOps(key).rangeByScore(start, end);
/* */ }
/* */
/* */
/* */ public Set<Object> getZSetReverseRangeByScore(String key, double start, double end) {
/* 286 */ return this.redisTemplate.boundZSetOps(key).reverseRangeByScore(start, end);
/* */ }
/* */
/* */
/* */ public Set<ZSetOperations.TypedTuple<Object>> getZSetRangeWithScores(String key, long start, long end) {
/* 291 */ return this.redisTemplate.boundZSetOps(key).rangeWithScores(start, end);
/* */ }
/* */
/* */
/* */ public Set<ZSetOperations.TypedTuple<Object>> getZSetReverseRangeWithScores(String key, long start, long end) {
/* 296 */ return this.redisTemplate.boundZSetOps(key).reverseRangeWithScores(start, end);
/* */ }
/* */
/* */
/* */ public Set<ZSetOperations.TypedTuple<Object>> getZSetRangeWithScores(String key) {
/* 301 */ return getZSetRangeWithScores(key, 0L, getZSetSize(key));
/* */ }
/* */
/* */
/* */ public Set<ZSetOperations.TypedTuple<Object>> getZSetReverseRangeWithScores(String key) {
/* 306 */ return getZSetReverseRangeWithScores(key, 0L, getZSetSize(key));
/* */ }
/* */
/* */
/* */ public long getZSetCountSize(String key, double sMin, double sMax) {
/* 311 */ return this.redisTemplate.boundZSetOps(key).count(sMin, sMax).longValue();
/* */ }
/* */
/* */
/* */ public long getZSetSize(String key) {
/* 316 */ return this.redisTemplate.boundZSetOps(key).size().longValue();
/* */ }
/* */
/* */
/* */ public double getZSetScore(String key, Object value) {
/* 321 */ return this.redisTemplate.boundZSetOps(key).score(value).doubleValue();
/* */ }
/* */
/* */
/* */ public double incrementZSetScore(String key, Object value, double delta) {
/* 326 */ return this.redisTemplate.boundZSetOps(key).incrementScore(value, delta).doubleValue();
/* */ }
/* */
/* */
/* */ public Boolean addZSet(String key, double score, Object value) {
/* 331 */ return this.redisTemplate.boundZSetOps(key).add(value, score);
/* */ }
/* */
/* */
/* */ public Long addZSet(String key, TreeSet<Object> value) {
/* 336 */ return this.redisTemplate.boundZSetOps(key).add(value);
/* */ }
/* */
/* */
/* */ public Boolean addZSet(String key, double[] score, Object[] value) {
/* 341 */ if (score.length != value.length) {
/* 342 */ return Boolean.valueOf(false);
/* */ }
/* 344 */ for (int i = 0; i < score.length; i++) {
/* 345 */ if (!addZSet(key, score[i], value[i]).booleanValue()) {
/* 346 */ return Boolean.valueOf(false);
/* */ }
/* */ }
/* 349 */ return Boolean.valueOf(true);
/* */ }
/* */
/* */
/* */ public void remove(String key) {
/* 354 */ if (exists(key)) {
/* 355 */ this.redisTemplate.delete(key);
/* */ }
/* */ }
/* */
/* */
/* */ public void removeZSetRangeByScore(String key, double s, double e) {
/* 361 */ this.redisTemplate.boundZSetOps(key).removeRangeByScore(s, e);
/* */ }
/* */
/* */
/* */ public Boolean setSetExpireTime(String key, Long time) {
/* 366 */ return this.redisTemplate.boundSetOps(key).expire(time.longValue(), TimeUnit.SECONDS);
/* */ }
/* */
/* */
/* */ public Boolean setZSetExpireTime(String key, Long time) {
/* 371 */ return this.redisTemplate.boundZSetOps(key).expire(time.longValue(), TimeUnit.SECONDS);
/* */ }
/* */
/* */
/* */ public boolean exists(String key) {
/* 376 */ return this.redisTemplate.hasKey(key).booleanValue();
/* */ }
/* */
/* */
/* */ public void delKey(String key) {
/* 381 */ this.redisTemplate.delete(key);
/* */ }
/* */
/* */
/* */ public Object get(String key) {
/* 386 */ return this.redisTemplate.boundValueOps(key).get();
/* */ }
/* */
/* */
/* */ public List<Object> get(String... keys) {
/* 391 */ List<Object> list = new ArrayList();
/* 392 */ for (String key : keys) {
/* 393 */ list.add(get(key));
/* */ }
/* 395 */ return list;
/* */ }
/* */
/* */
/* */ public List<Object> getByRegular(String regKey) {
/* 400 */ Set<String> stringSet = getAllKeys();
/* 401 */ List<Object> objectList = new ArrayList();
/* 402 */ for (String s : stringSet) {
/* 403 */ if (Pattern.compile(regKey).matcher(s).matches() && getType(s) == DataType.STRING) {
/* 404 */ objectList.add(get(s));
/* */ }
/* */ }
/* 407 */ return objectList;
/* */ }
/* */
/* */
/* */ public void set(String key, Object value) {
/* 412 */ this.redisTemplate.boundValueOps(key).set(value);
/* */ }
/* */
/* */
/* */ public void set(String key, Object value, Long expireTime) {
/* 417 */ this.redisTemplate.boundValueOps(key).set(value, expireTime.longValue(), TimeUnit.SECONDS);
/* */ }
/* */
/* */
/* */ public boolean setExpireTime(String key, Long expireTime) {
/* 422 */ return this.redisTemplate.expire(key, expireTime.longValue(), TimeUnit.SECONDS).booleanValue();
/* */ }
/* */
/* */
/* */
/* */ public DataType getType(String key) {
/* 428 */ return this.redisTemplate.type(key);
/* */ }
/* */
/* */
/* */
/* */ public void removeMapField(String key, Object... field) {
/* 434 */ this.redisTemplate.boundHashOps(key).delete(field);
/* */ }
/* */
/* */
/* */ public Long getMapSize(String key) {
/* 439 */ return this.redisTemplate.boundHashOps(key).size();
/* */ }
/* */
/* */
/* */ public Map<String, Object> getMap(String key) {
/* 444 */ return this.redisTemplate.boundHashOps(key).entries();
/* */ }
/* */
/* */
/* */ public <T> T getMapField(String key, String field) {
/* 449 */ return (T)this.redisTemplate.boundHashOps(key).get(field);
/* */ }
/* */
/* */
/* */ public Boolean hasMapKey(String key, String field) {
/* 454 */ return this.redisTemplate.boundHashOps(key).hasKey(field);
/* */ }
/* */
/* */
/* */ public List<Object> getMapFieldValue(String key) {
/* 459 */ return this.redisTemplate.boundHashOps(key).values();
/* */ }
/* */
/* */
/* */ public Set<Object> getMapFieldKey(String key) {
/* 464 */ return this.redisTemplate.boundHashOps(key).keys();
/* */ }
/* */
/* */
/* */ public void addMap(String key, Map<String, Object> map) {
/* 469 */ this.redisTemplate.boundHashOps(key).putAll(map);
/* */ }
/* */
/* */
/* */ public void addMap(String key, String field, Object value) {
/* 474 */ this.redisTemplate.boundHashOps(key).put(field, value);
/* */ }
/* */
/* */
/* */ public void addMap(String key, String field, Object value, long time) {
/* 479 */ this.redisTemplate.boundHashOps(key).put(field, value);
/* 480 */ this.redisTemplate.boundHashOps(key).expire(time, TimeUnit.SECONDS);
/* */ }
/* */
/* */
/* */ public void watch(String key) {
/* 485 */ this.redisTemplate.watch(key);
/* */ }
/* */
/* */
/* */ public void addSet(String key, Object... obj) {
/* 490 */ this.redisTemplate.boundSetOps(key).add(obj);
/* */ }
/* */
/* */
/* */ public long removeSetValue(String key, Object obj) {
/* 495 */ return this.redisTemplate.boundSetOps(key).remove(new Object[] { obj }).longValue();
/* */ }
/* */
/* */
/* */ public long removeSetValue(String key, Object... obj) {
/* 500 */ if (obj != null && obj.length > 0) {
/* 501 */ return this.redisTemplate.boundSetOps(key).remove(obj).longValue();
/* */ }
/* 503 */ return 0L;
/* */ }
/* */
/* */
/* */ public long getSetSize(String key) {
/* 508 */ return this.redisTemplate.boundSetOps(key).size().longValue();
/* */ }
/* */
/* */
/* */ public Boolean hasSetValue(String key, Object obj) {
/* 513 */ Boolean boo = null;
/* 514 */ int t = 0;
/* */ while (true) {
/* */ try {
/* 517 */ boo = this.redisTemplate.boundSetOps(key).isMember(obj);
/* */ break;
/* 519 */ } catch (Exception e) {
/* 520 */ this.logger.error("key[" + key + "],obj[" + obj + "]判断Set中的值是否存在失败,异常信息:" + e.getMessage());
/* 521 */ t++;
/* */
/* 523 */ if (t > times.intValue())
/* */ break;
/* */ }
/* */ }
/* 527 */ this.logger.info("key[" + key + "],obj[" + obj + "]是否存在,boo:" + boo);
/* 528 */ return boo;
/* */ }
/* */
/* */
/* */ public Set<Object> getSet(String key) {
/* 533 */ return this.redisTemplate.boundSetOps(key).members();
/* */ }
/* */
/* */
/* */ public Set<Object> getSetUnion(String key, String otherKey) {
/* 538 */ return this.redisTemplate.boundSetOps(key).union(otherKey);
/* */ }
/* */
/* */
/* */ public Set<Object> getSetUnion(String key, Set<Object> set) {
/* 543 */ return this.redisTemplate.boundSetOps(key).union(set);
/* */ }
/* */
/* */
/* */ public Set<Object> getSetIntersect(String key, String otherKey) {
/* 548 */ return this.redisTemplate.boundSetOps(key).intersect(otherKey);
/* */ }
/* */
/* */
/* */ public Set<Object> getSetIntersect(String key, Set<Object> set) {
/* 553 */ return this.redisTemplate.boundSetOps(key).intersect(set);
/* */ }
/* */ }
/* */ import com.fasterxml.jackson.annotation.JsonAutoDetect;
/* */ import com.fasterxml.jackson.annotation.PropertyAccessor;
/* */ import com.fasterxml.jackson.databind.ObjectMapper;
/* */ import org.crazycake.shiro.RedisCacheManager;
/* */ import org.crazycake.shiro.RedisManager;
/* */ import org.springframework.beans.factory.annotation.Qualifier;
/* */ import org.springframework.beans.factory.annotation.Value;
/* */ import org.springframework.context.annotation.Bean;
/* */ import org.springframework.context.annotation.Configuration;
/* */ import org.springframework.data.redis.connection.RedisConnectionFactory;
/* */ import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
/* */ import org.springframework.data.redis.core.RedisTemplate;
/* */ import org.springframework.data.redis.core.StringRedisTemplate;
/* */ import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
/* */ import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
/* */ import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
/* */ import org.springframework.data.redis.serializer.RedisSerializer;
/* */ import org.springframework.data.redis.serializer.StringRedisSerializer;
/* */ import redis.clients.jedis.JedisPoolConfig;
/* */
/* */
/* */ @Configuration
/* */ public class RedisConfig
/* */ {
/* */ @Value("${redis.maxIdle}")
/* */ private Integer maxIdle;
/* */ @Value("${redis.maxTotal}")
/* */ private Integer maxTotal;
/* */ @Value("${redis.maxWaitMillis}")
/* */ private Integer maxWaitMillis;
/* */ @Value("${redis.minEvictableIdleTimeMillis}")
/* */ private Integer minEvictableIdleTimeMillis;
/* */ @Value("${redis.numTestsPerEvictionRun}")
/* */ private Integer numTestsPerEvictionRun;
/* */ @Value("${redis.timeBetweenEvictionRunsMillis}")
/* */ private long timeBetweenEvictionRunsMillis;
/* */ @Value("${redis.testOnBorrow}")
/* */ private boolean testOnBorrow;
/* */ @Value("${redis.testWhileIdle}")
/* */ private boolean testWhileIdle;
/* */ @Value("${redis.testOnReturn}")
/* */ private boolean testOnReturn;
/* */ @Value("${redis.hostName}")
/* */ private String redisHostName;
/* */ @Value("${redis.port}")
/* */ private Integer redisPort;
/* */ @Value("${redis.timeout}")
/* */ private Integer timeout;
/* */ @Value("${redis.password}")
/* */ private String password;
/* */ @Value("${redis.expire}")
/* */ private Integer expire;
/* */
/* */ @Bean
/* */ public JedisPoolConfig jedisPoolConfig() {
/* 80 */ JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
/* */
/* 82 */ jedisPoolConfig.setMaxIdle(this.maxIdle.intValue());
/* */
/* 84 */ jedisPoolConfig.setMaxTotal(this.maxTotal.intValue());
/* */
/* 86 */ jedisPoolConfig.setMaxWaitMillis(this.maxWaitMillis.intValue());
/* */
/* 88 */ jedisPoolConfig.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis.intValue());
/* */
/* 90 */ jedisPoolConfig.setNumTestsPerEvictionRun(this.numTestsPerEvictionRun.intValue());
/* */
/* 92 */ jedisPoolConfig.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
/* */
/* 94 */ jedisPoolConfig.setTestOnBorrow(this.testOnBorrow);
/* */
/* 96 */ jedisPoolConfig.setTestWhileIdle(this.testWhileIdle);
/* 97 */ jedisPoolConfig.setTestOnReturn(this.testOnReturn);
/* 98 */ return jedisPoolConfig;
/* */ }
/* */
/* */
/* */
/* */
/* */ @Bean
/* */ public JedisConnectionFactory JedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
/* 114 */ JedisConnectionFactory JedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig);
/* */
/* 116 */ JedisConnectionFactory.setPoolConfig(jedisPoolConfig);
/* */
/* 118 */ JedisConnectionFactory.setHostName(this.redisHostName);
/* */
/* 120 */ JedisConnectionFactory.setPort(this.redisPort.intValue());
/* */
/* 122 */ JedisConnectionFactory.setPassword(this.password);
/* */
/* 124 */ JedisConnectionFactory.setTimeout(this.timeout.intValue());
/* 125 */ return JedisConnectionFactory;
/* */ }
/* */
/* */
/* */ @Bean({"ShiroRedisTemplate"})
/* */ public RedisTemplate shiroRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
/* 149 */ StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory);
/* 150 */ template.setKeySerializer((RedisSerializer)new JdkSerializationRedisSerializer());
/* 151 */ template.setValueSerializer((RedisSerializer)new JdkSerializationRedisSerializer());
/* 152 */ template.setHashKeySerializer((RedisSerializer)new JdkSerializationRedisSerializer());
/* 153 */ template.setHashValueSerializer((RedisSerializer)new JdkSerializationRedisSerializer());
/* 154 */ template.afterPropertiesSet();
/* */
/* */
/* 157 */ template.setConnectionFactory(redisConnectionFactory);
/* 158 */ return (RedisTemplate)template;
/* */ }
/* */
/* */
/* */ @Bean({"RedisTemplateUtils"})
/* */ public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
/* 168 */ StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory);
/* */
/* 170 */ Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
/* 171 */ ObjectMapper om = new ObjectMapper();
/* 172 */ om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
/* 173 */ om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
/* 174 */ jackson2JsonRedisSerializer.setObjectMapper(om);
/* 175 */ template.setValueSerializer((RedisSerializer)jackson2JsonRedisSerializer);
/* 176 */ template.setHashValueSerializer((RedisSerializer)jackson2JsonRedisSerializer);
/* 177 */ template.afterPropertiesSet();
/* */
/* 179 */ template.setEnableTransactionSupport(true);
/* 180 */ template.setConnectionFactory(redisConnectionFactory);
/* */
/* */
/* */
/* 190 */ return (RedisTemplate)template;
/* */ }
/* */
/* */
/* */ private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
/* 201 */ redisTemplate.setKeySerializer((RedisSerializer)new StringRedisSerializer());
/* 202 */ redisTemplate.setHashKeySerializer((RedisSerializer)new StringRedisSerializer());
/* 203 */ redisTemplate.setHashValueSerializer((RedisSerializer)new GenericJackson2JsonRedisSerializer());
/* 204 */ redisTemplate.setValueSerializer((RedisSerializer)new GenericJackson2JsonRedisSerializer());
/* */
/* */
/* 207 */ redisTemplate.setConnectionFactory(factory);
/* */ }
/* */
/* */
/* */
/* */
/* */ @Bean({"shiroSpringCacheManager"})
/* */ public RedisCacheManager cacheManager(@Qualifier("redisManager") RedisManager redisManager) {
/* 234 */ RedisCacheManager redisCacheManager = new RedisCacheManager();
/* 235 */ redisCacheManager.setRedisManager(redisManager);
/* 236 */ return redisCacheManager;
/* */ }
/* */ @Bean(name = {"redisManager"})
/* */ public RedisManager redisManager() {
/* 247 */ RedisManager redisManager = new RedisManager();
/* 248 */ redisManager.setHost(this.redisHostName);
/* 249 */ redisManager.setPort(this.redisPort.intValue());
/* 250 */ redisManager.setExpire(this.expire.intValue());
/* 251 */ redisManager.setTimeout(this.timeout.intValue());
/* 252 */ redisManager.setPassword(this.password);
/* 253 */ return redisManager;
/* */ }
/* */ }
# redis 配置
spring:
redis:
# 地址
host: localhost
# 端口,默认为6379
port: 6379
# 密码
password:
# 连接超时时间
timeout: 10s
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 8
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
配置B:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
/**
* spring redis 工具类
*
* @author ruoyi
**/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{
@Autowired
public RedisTemplate redisTemplate;
/**
* 缓存基本的对象,Integer、String、实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
* @return 缓存的对象
*/
public <T> ValueOperations<String, T> setCacheObject(String key, T value)
{
ValueOperations<String, T> operation = redisTemplate.opsForValue();
operation.set(key, value);
return operation;
}
/**
* 缓存基本的对象,Integer、String、实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
* @param timeout 时间
* @param timeUnit 时间颗粒度
* @return 缓存的对象
*/
public <T> ValueOperations<String, T> setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit)
{
ValueOperations<String, T> operation = redisTemplate.opsForValue();
operation.set(key, value, timeout, timeUnit);
return operation;
}
/**
* 获得缓存的基本对象。
*
* @param key 缓存键值
* @return 缓存键值对应的数据
*/
public <T> T getCacheObject(String key)
{
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
* 删除单个对象
*
* @param key
*/
public void deleteObject(String key)
{
redisTemplate.delete(key);
}
/**
* 删除集合对象
*
* @param collection
*/
public void deleteObject(Collection collection)
{
redisTemplate.delete(collection);
}
/**
* 缓存List数据
*
* @param key 缓存的键值
* @param dataList 待缓存的List数据
* @return 缓存的对象
*/
public <T> ListOperations<String, T> setCacheList(String key, List<T> dataList)
{
ListOperations listOperation = redisTemplate.opsForList();
if (null != dataList)
{
int size = dataList.size();
for (int i = 0; i < size; i++)
{
listOperation.leftPush(key, dataList.get(i));
}
}
return listOperation;
}
/**
* 获得缓存的list对象
*
* @param key 缓存的键值
* @return 缓存键值对应的数据
*/
public <T> List<T> getCacheList(String key)
{
List<T> dataList = new ArrayList<T>();
ListOperations<String, T> listOperation = redisTemplate.opsForList();
Long size = listOperation.size(key);
for (int i = 0; i < size; i++)
{
dataList.add(listOperation.index(key, i));
}
return dataList;
}
/**
* 缓存Set
*
* @param key 缓存键值
* @param dataSet 缓存的数据
* @return 缓存数据的对象
*/
public <T> BoundSetOperations<String, T> setCacheSet(String key, Set<T> dataSet)
{
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext())
{
setOperation.add(it.next());
}
return setOperation;
}
/**
* 获得缓存的set
*
* @param key
* @return
*/
public <T> Set<T> getCacheSet(String key)
{
Set<T> dataSet = new HashSet<T>();
BoundSetOperations<String, T> operation = redisTemplate.boundSetOps(key);
dataSet = operation.members();
return dataSet;
}
/**
* 缓存Map
*
* @param key
* @param dataMap
* @return
*/
public <T> HashOperations<String, String, T> setCacheMap(String key, Map<String, T> dataMap)
{
HashOperations hashOperations = redisTemplate.opsForHash();
if (null != dataMap)
{
for (Map.Entry<String, T> entry : dataMap.entrySet())
{
hashOperations.put(key, entry.getKey(), entry.getValue());
}
}
return hashOperations;
}
/**
* 获得缓存的Map
*
* @param key
* @return
*/
public <T> Map<String, T> getCacheMap(String key)
{
Map<String, T> map = redisTemplate.opsForHash().entries(key);
return map;
}
/**
* 获得缓存的基本对象列表
*
* @param pattern 字符串前缀
* @return 对象列表
*/
public Collection<String> keys(String pattern)
{
return redisTemplate.keys(pattern);
}
}
配置C:
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.lang.reflect.Method;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* 生成key的策略
* @return
*/
@Override
@Bean
public KeyGenerator keyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for(Object obj : params){
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* 管理缓存
* @param factory
* @return
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory){
RedisCacheManager cacheManager = RedisCacheManager.create(factory);
return cacheManager;
}
/**
* RedisTemplate配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory factory){
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
redis.properties
redis.hostName=127.0.0.1
redis.port=6379
redis.password=
redis.timeout=10000
redis.maxIdle=300
#redis.maxActive=600
redis.maxTotal=1000
redis.maxWaitMillis=1000
redis.minEvictableIdleTimeMillis=300000
redis.numTestsPerEvictionRun=1024
redis.timeBetweenEvictionRunsMillis=30000
redis.testOnBorrow=true
redis.testWhileIdle=true
#spring.redis.cluster.nodes=192.168.177.128:7001,192.168.177.128:7002,192.168.177.128:7003,192.168.177.128:7004,192.168.177.128:7005,192.168.177.128:7006
#spring.redis.cluster.max-redirects=3
#redis.sentinel.host1=192.168.177.128
#redis.sentinel.port1=26379
#redis.sentinel.host2=172.20.1.231
#redis.sentinel.port2=26379
/**
* 加载权限菜单 通过用户roleList,如有权限菜单重复则去除
* 如果有多个role去除可能role对应重复的emenu,并留下交叉的
* 根据用户实例,用户角色list作为key存储redis,下次不再查询节约资源
* 使用会员实例+roleList为key,当变动role时,更新allMenu
* @param parentId
* @return
*/
@ApiOperation(value = "读取系统菜单", notes = "[待改善]树形结构,根据roleid按需获取,而不是显示没有权限访问")
@Cacheable(value = "allMenu", key = "#session.getAttribute('menuIds').toString()+#session.getAttribute('currentUser').toString()", condition = "#parentId != '' ")
@ResponseBody
@PostMapping("/loadMenuInfo")
@RequiresAuthentication
@RequiresPermissions("系统菜单")
public String loadMenuInfo(HttpSession session, Integer parentId) {
System.out.println("读取系统菜单中");
String allMenu = "";
allMenu = (String) redisService.get(session.getAttribute("menuIds").toString() + session.getAttribute("currentUser").toString());
if (allMenu.length() > 0) {
System.out.println("通过redis获取session的menuids+currentUser获取了allMenu");
return allMenu;
}
Object menuIdArr = session.getAttribute("menuIds");
int[] menuIds = (int[]) menuIdArr;
Arrays.sort(menuIds);
String menuIdStr = "";
for (int menuId : menuIds) {
menuIdStr += menuId + ",";
}
if (redisService.get(menuIdStr) != null) {
System.out.println("loadMenuInfo获取到了redis中的allMenu数据");
allMenu = redisService.get(menuIdStr).toString();
return allMenu;
} else {
System.out.println("loadMenuInfo从redis中获取allMenu数据失败.");
Object menuIdArr1 = session.getAttribute("menuIds");
int[] menuIds1 = (int[]) menuIdArr1;
Arrays.sort(menuIds);
String menuIdStr1 = "";
for (int menuId : menuIds1) {
menuIdStr1 += menuId + ",";
}
System.out.println("menuIdStr1:" + menuIdStr1);
Object allMenuObj = redisService.get(menuIdStr1);
if (allMenuObj != null) {
System.out.println("(String)allMenuObj:" + allMenuObj.toString());
System.out.println("loadMenuInfo获取到了redis中的allMenu数据,第二次成功.");
allMenu = allMenuObj.toString();
return allMenu;
} else {
System.out.println("loadMenuInfo从redis中获取allMenu数据失败.正式开始走数据库获取.");
allMenu = eMenuUtils.getAllEMenuByParentIdAndMenuIds(parentId, menuIds).toString();
System.out.println("loadMenuInfo获取数据库后,allMenu:" + allMenu);
redisService.set(menuIdStr1, allMenu);
return allMenu;
}
}
}
配置D:
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@ConfigurationProperties(prefix = "spring.cache.redis")
public class RedisCacheConfig {
private Duration timeToLive = Duration.ZERO;
public void setTimeToLive(Duration timeToLive) {
this.timeToLive = timeToLive;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.PUBLIC_ONLY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(timeToLive)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
配置D(2):
# Mybatis 配置
mybatis:
configuration:
cache-enabled: true
default-statement-timeout: 3000
map-underscore-to-camel-case: true
use-generated-keys: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath*:mybatis/mapper/*Mapper.xml
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author zq
*/
@Configuration
@ConfigurationProperties(prefix = "spring.cache.redis")
public class RedisCacheConfig {
private Duration timeToLive = Duration.ZERO;
public void setTimeToLive(Duration timeToLive) {
this.timeToLive = timeToLive;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.PUBLIC_ONLY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(timeToLive)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 当--号创建,更新,删除后的这些种种update操作时
* 调用freshResultInterest重新刷入缓存
*
* @author zq
* @date 2020-01-05
*/
@Service
@CacheConfig(cacheNames = "interest_search_results")
public class ResultInterestServiceImpl implements IResultInterestService {
@Autowired
private InterestMapper interestMapper;
private List<InterestDo> interestResultDatas;
@Override
@HystrixCommand(fallbackMethod = "db_not_connected")
public List<InterestDo> freshResultInterest(String code) {
interestResultDatas = fetchIndexesFromDB(code);
IResultInterestService resultInterestService = SpringContextUtil.getBean(IResultInterestService.class);
resultInterestService.removeOldRedisData(code);
return resultInterestService.storeResultInterest(code);
}
private List<InterestDo> getInterestFromDBIfNoCache(String code) {
List<InterestDo> interestLists = fetchIndexesFromDB(code);
return interestLists;
}
@Override
@Cacheable(key = "'result_interest_'+#p0")
public List<InterestDo> getResultInterest(String code) {
return getInterestFromDBIfNoCache(code);
}
@Override
@CachePut(key = "'result_interest_'+#p0")
public List<InterestDo> storeResultInterest(String code) {
return interestResultDatas;
}
@Override
@CacheEvict(key = "'result_interest_'+#p0")
public void removeOldRedisData(String code) {
//nothing ,just CacheEvict
}
@Override
public List<InterestDo> fetchIndexesFromDB(String code) {
List<InterestDo> interestDos = interestMapper.
selectList(new LambdaQueryWrapper<InterestDo>().
like(InterestDo::getTitle, code).
orderByDesc(InterestDo::getCreateTime));
System.out.println(interestDos.size());
return interestDos;
}
@Override
public List<InterestDo> db_not_connected(String code) {
System.out.println("db_not_connected()");
InterestDo interest = new InterestDo();
interest.setTitle("无效指令");
interest.setId(0L);
interest.setHeadImg("请检查参数");
return CollectionUtil.toList(interest);
}
}
配置E:
import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
/**
* redis 缓存工具类
* @author
*/
@Component
public class RedisCacheUtil {
@Resource
private RedisTemplate<String, String> redisTemplate;
private static RedisCacheUtil redisCacheUtil;
@PostConstruct
public void init(){
redisCacheUtil = this;
redisCacheUtil.redisTemplate = this.redisTemplate;
}
/**
* 缓存字符换,json字符串等数据类型
* @param key
* @param value
*/
public static void setString(String key, String value){
ValueOperations<String, String> valueOperations = redisCacheUtil.redisTemplate.opsForValue();
valueOperations.set(key, value);
}
/**
* 把对象转为Json字符串存入缓存
* @param key
* @param t
* @param <T>
*/
public static <T> void setBeanToJsonStr(String key, T t){
String ts = JSON.toJSONString(t);
setString(key, ts);
}
/**
* 根据key,相应的类型 获取相应的对象
* @param key
* @param clazz
* @param <T>
* @return
*/
public static <T> T getJsonBean(String key, Class<T> clazz){
String value = redisCacheUtil.redisTemplate.opsForValue().get(key);
if(value == null){
return null;
}
return JSON.parseObject(value, clazz);
}
/**
* 根据key,相应的类型 获取相应的对象
* @param key
* @return
*/
public static String getString(String key){
String value = redisCacheUtil.redisTemplate.opsForValue().get(key);
return value;
}
}
# redis 配置信息 (暂时没配置集群)
redis:
hostName: redis
host: redis
maxIdle: 300
maxTotal: 1000
maxWaitMillis: 1000
minEvictableIdleTimeMillis: 300000
numTestsPerEvictionRun: 1024
password:
port: 6379
testOnBorrow: true
testWhileIdle: true
timeBetweenEvictionRunsMillis: 30000
timeout: 10000
https://www.cnblogs.com/ukzq/p/10763133.html
https://www.cnblogs.com/ukzq/p/10205176.html