@Override @SuppressWarnings({"rawtypes", "unchecked"}) public Integer updatetag(Integer tId) { //标签 List<Tag> tags = tagMapper.getAllTags(); JsonArray jsonArray = new JsonArray(); for (Tag tag : tags) { List<Blog> blogs = tagMapper.getblogbytagid(tag.gettId()); String str = tag.gettName() + " " + "(" + String.valueOf(blogs.size()) + ")"; KeyAndValue keyAndValue = new KeyAndValue(); keyAndValue.setKey(tag.gettName()); keyAndValue.setValue(str); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("key", tag.gettId()); jsonObject.addProperty("value", str); jsonArray.add(jsonObject); } boolean result = redisTemplate.execute((RedisCallback<Boolean>) connection -> { RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); connection.set(serializer.serialize("biaoqian"), serializer.serialize(jsonArray.toString())); return true; }); return tId; }
@Override public void put(Object key, Object value) { final String keyf = (String) key; final Object valuef = value; final long liveTime = 86400; redisTemplate.execute(new RedisCallback<Long>() { public Long doInRedis(RedisConnection connection) throws DataAccessException { byte[] keyb = keyf.getBytes(); byte[] valueb = toByteArray(valuef); connection.set(keyb, valueb); if (liveTime > 0) { connection.expire(keyb, liveTime); } return 1L; } }); }
/** * 根据key获取对象 * * @param keyPatten the key patten * @return the keys values */ public Map<String, String> getKeysValues(final String keyPatten) { LOGGER.info("[redisTemplate redis] getValues() patten={} ", keyPatten); return redisTemplate.execute((RedisCallback<Map<String, String>>) connection -> { RedisSerializer<String> serializer = getRedisSerializer(); Map<String, String> maps = new HashMap<>(); Set<String> keys = redisTemplate.keys(keyPatten + "*"); for (String key : keys) { byte[] bKeys = serializer.serialize(key); byte[] bValues = connection.get(bKeys); String value = serializer.deserialize(bValues); maps.put(key, value); } return maps; }); }
@Override public void updateAll() { try { final List<Viapp> list = appDao.getAllApp(); logger.info("BeginNewAddAppToRedis..."); long start = System.currentTimeMillis(); redisTemplate.execute(new RedisCallback<Object>() { @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.flushDb(); //connection.multi(); commonRedis.saveCommonRedis(list,connection); // connection.exec(); return null; } }); logger.info("redis init finish cost:{}ms!", System.currentTimeMillis() - start); }catch(Exception e){ e.printStackTrace(); } }
@Override public List<RequestStatics> getServerServiceRequests(final String serverIp, final String serviceId) throws Exception { return stringRedisTemplate.execute(new RedisCallback<List<RequestStatics>>() { public List<RequestStatics> doInRedis(RedisConnection connection) throws DataAccessException { String k = Constants.REDIS_SERVER_PREFIX + serverIp + "_" + serviceId; StringRedisConnection conn = ((StringRedisConnection)connection); Set<StringTuple> callers = conn.zRangeByScoreWithScores(k, Long.MIN_VALUE, Long.MAX_VALUE); if (callers.isEmpty()){ return Collections.EMPTY_LIST; } List<RequestStatics> res = new ArrayList<RequestStatics>(); for (StringTuple tuple:callers){ Double score = tuple.getScore(); String value = tuple.getValueAsString(); RequestStatics statics = new RequestStatics(); statics.setTime(score.longValue()); statics.setCount(Integer.parseInt(value)); res.add(statics); } Collections.sort(res); return res; } }); }
public static String getString(final String key, final Long seconds) { String result = (String) redisTemplate.execute(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { try { byte[] byteKey = key.getBytes("utf-8"); byte[] value = connection.get(byteKey); if (value == null) { return null; } if (seconds != null) { connection.expire(byteKey, seconds); } return new String(value, "utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("不支持的编码类型utf-8", e); } } }, true, false); return result; }
public static void hSetString(final String key, final String field, final String value, final Long seconds) { redisTemplate.execute(new RedisCallback() { @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { try { byte[] byteKey = key.getBytes("utf-8"); connection.hSet(byteKey, field.getBytes("utf-8"), value.getBytes("utf-8")); if (seconds != null) { connection.expire(byteKey, seconds); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("不支持的编码类型utf-8", e); } return null; } }, true, true); }
@Override public List<CodeStatics> getServerServiceCodes(final String serverIp, final String serviceId) throws Exception { return stringRedisTemplate.execute(new RedisCallback<List<CodeStatics>>() { public List<CodeStatics> doInRedis(RedisConnection connection) throws DataAccessException { String k = Constants.REDIS_SERVER_CODE_PREFIX + serverIp + "_" + serviceId; StringRedisConnection conn = ((StringRedisConnection)connection); Set<StringTuple> callers = conn.zRangeByScoreWithScores(k, Long.MIN_VALUE, Long.MAX_VALUE); if (callers.isEmpty()){ return Collections.EMPTY_LIST; } List<CodeStatics> res = new ArrayList<CodeStatics>(); for (StringTuple tuple:callers){ Double score = tuple.getScore(); String value = tuple.getValueAsString(); CodeStatics statics = new CodeStatics(); statics.setTime(score.longValue()); statics.setScore(Double.parseDouble(value)); res.add(statics); } Collections.sort(res); return res; } }); }
@ManagedOperation(description = "Clear the store") @Override public void clear() { valueOperations.getOperations().execute(new RedisCallback<List<byte[]>>() { @Override public List<byte[]> doInRedis(RedisConnection connection) throws DataAccessException { List<byte[]> binaryKeys = new ArrayList<>(); Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match("*" + createRedisKey("*")).build()); while (cursor.hasNext()) { byte[] key = cursor.next(); binaryKeys.add(key); } if (binaryKeys.size() > 0) { connection.del(binaryKeys.toArray(new byte[][]{})); } return binaryKeys; } }); }
@SuppressWarnings("unchecked") protected Set<String> loadRemoteCacheKeys() { return (Set<String>) template.execute(new RedisCallback<Set<String>>() { @Override public Set<String> doInRedis(RedisConnection connection) throws DataAccessException { // we are using the ~keys postfix as defined in RedisCache#setName Set<byte[]> keys = connection.keys(template.getKeySerializer().serialize("*~keys")); Set<String> cacheKeys = new LinkedHashSet<String>(); if (!CollectionUtils.isEmpty(keys)) { for (byte[] key : keys) { cacheKeys.add(template.getKeySerializer().deserialize(key).toString().replace("~keys", "")); } } return cacheKeys; } }); }
@SuppressWarnings("unchecked") public void put(final Object key, final Object value,final Long expireTime) { final byte[] keyBytes = computeKey(key); final byte[] valueBytes = convertToBytesIfNecessary(redisTemplate.getValueSerializer(), value); redisTemplate.execute(new RedisCallback<Object>() { public Object doInRedis(RedisConnection connection) throws DataAccessException { waitForLock(connection); connection.multi(); connection.set(keyBytes, valueBytes); connection.zAdd(setName, 0, keyBytes); if (expireTime!=null && expireTime!=0L) { connection.expire(keyBytes, expireTime); connection.expire(setName, expireTime); } connection.exec(); return null; } }, true); }
@Override public boolean update(final String key, final String value) { if (get(key) == null) { throw new NullPointerException("数据行不存在, key = " + key); } boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); byte[] keyStr = serializer.serialize(key); byte[] valueStr = serializer.serialize(value); connection.set(keyStr, valueStr); return true; } }); return result; }
/** * 删除历史数据 * 根据key值找到图片的名称 */ @Deprecated public void deleteTieBaImageTypeOne() { redisTemplate.execute(new RedisCallback<Object>() { public Object doInRedis(RedisConnection redisConnection) throws DataAccessException { byte[] imageKey = getByte(TieBaImageIdMessageListener.TIEBA_CONTENT_IMAGE_KEY + "*"); long beginTime = System.currentTimeMillis(); Set<byte[]> keys = redisConnection.keys(imageKey); log.info("模糊查询耗时:{}", (System.currentTimeMillis() - beginTime) + "ms"); //判断key for (byte[] key : keys) { try { byte[] image = redisConnection.get(key); List<String> imageUrlList = JSONObject.parseObject(image, List.class); // qiNiuUtil.deleteByList(imageUrlList); qiNiuUtil.getDeleteBlockingDeque().put(imageUrlList); } catch (Exception e) { log.error("删除图片失败!key {}", WebmagicService.getString(key)); } } return null; } }); }
@Override public List<CostsStatics> getServerServiceCosts(final String serverIp, final String serviceId) throws Exception { return stringRedisTemplate.execute(new RedisCallback<List<CostsStatics>>() { public List<CostsStatics> doInRedis(RedisConnection connection) throws DataAccessException { String k = Constants.REDIS_SERVER_COSTS_PREFIX + serverIp + "_" + serviceId; StringRedisConnection conn = ((StringRedisConnection)connection); Set<StringTuple> callers = conn.zRangeByScoreWithScores(k, Long.MIN_VALUE, Long.MAX_VALUE); if (callers.isEmpty()){ return Collections.EMPTY_LIST; } List<CostsStatics> res = new ArrayList<CostsStatics>(); for (StringTuple tuple:callers){ Double score = tuple.getScore(); String value = tuple.getValueAsString(); CostsStatics statics = new CostsStatics(); statics.setTime(score.longValue()); statics.setCosts(Long.parseLong(value)); res.add(statics); } Collections.sort(res); return res; } }); }
@Override public void delete(Collection<K> keys) { if (CollectionUtils.isEmpty(keys)) { return; } final byte[][] rawKeys = rawKeys(keys); execute(new RedisCallback<Object>() { public Object doInRedis(RedisConnection connection) { int dbIndex = RedisApplication.redisConnectionDbIndex.get(); connection.select(dbIndex); connection.del(rawKeys); return null; } }, true); }
public static String hGetString(final String key, final String field, final Long seconds) { String result = (String) redisTemplate.execute(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { try { byte[] byteKey = key.getBytes("utf-8"); byte[] value = connection.hGet(byteKey, field.getBytes("utf-8")); if (value == null) { return null; } if (seconds != null) { connection.expire(byteKey, seconds); } return new String(value, "utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("不支持的编码类型utf-8", e); } } }, true, false); return result; }
@Override public Cursor<V> scan(K key, final ScanOptions options) { final byte[] rawKey = rawKey(key); return execute(new RedisCallback<Cursor<V>>() { @Override public Cursor<V> doInRedis(RedisConnection connection) throws DataAccessException { return new ConvertingCursor<byte[], V>(connection.sScan(rawKey, options), new Converter<byte[], V>() { @Override public V convert(byte[] source) { return deserializeValue(source); } }); } }, true); }
public void multiSet(Map<? extends K, ? extends V> m) { if (m.isEmpty()) { return; } final Map<byte[], byte[]> rawKeys = new LinkedHashMap<byte[], byte[]>(m.size()); for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { rawKeys.put(rawKey(entry.getKey()), rawValue(entry.getValue())); } execute(new RedisCallback<Object>() { public Object doInRedis(RedisConnection connection) { connection.select(dbIndex); connection.mSet(rawKeys); return null; } }, true); }
public Boolean multiSetIfAbsent(Map<? extends K, ? extends V> m) { if (m.isEmpty()) { return true; } final Map<byte[], byte[]> rawKeys = new LinkedHashMap<byte[], byte[]>(m.size()); for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { rawKeys.put(rawKey(entry.getKey()), rawValue(entry.getValue())); } return execute(new RedisCallback<Boolean>() { public Boolean doInRedis(RedisConnection connection) { connection.select(dbIndex); return connection.mSetNX(rawKeys); } }, true); }
public static void setString(final String key, final String value, final Long seconds) { redisTemplate.execute(new RedisCallback() { @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { try { byte[] byteKey = key.getBytes("utf-8"); connection.set(byteKey, value.getBytes("utf-8")); if (seconds != null) { connection.expire(byteKey, seconds); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("不支持的编码类型utf-8", e); } return null; } }, true, true); }
public void putAll(K key, Map<? extends HK, ? extends HV> m) { if (m.isEmpty()) { return; } final byte[] rawKey = rawKey(key); final Map<byte[], byte[]> hashes = new LinkedHashMap<byte[], byte[]>(m.size()); for (Map.Entry<? extends HK, ? extends HV> entry : m.entrySet()) { hashes.put(rawHashKey(entry.getKey()), rawHashValue(entry.getValue())); } execute(new RedisCallback<Object>() { public Object doInRedis(RedisConnection connection) { connection.select(dbIndex); connection.hMSet(rawKey, hashes); return null; } }, true); }
public List<HV> multiGet(K key, Collection<HK> fields) { if (fields.isEmpty()) { return Collections.emptyList(); } final byte[] rawKey = rawKey(key); final byte[][] rawHashKeys = new byte[fields.size()][]; int counter = 0; for (HK hashKey : fields) { rawHashKeys[counter++] = rawHashKey(hashKey); } List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() { public List<byte[]> doInRedis(RedisConnection connection) { connection.select(dbIndex); return connection.hMGet(rawKey, rawHashKeys); } }, true); return deserializeHashValues(rawValues); }
@Override public <T> List<T> getList(final String key, final Class<T> clazz) { List<T> result = redisTemplate.execute(new RedisCallback<List<T>>() { public List<T> doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); byte[] keyStr = serializer.serialize(key); byte[] value = connection.get(keyStr); if (value == null) { return null; } String valueStr = serializer.deserialize(value); return JSON.parseArray(valueStr, clazz); } }); return result; }
@Override public List<CallersStatics> getServerServiceCallers(final String serverIp, final String serviceId) throws Exception { return stringRedisTemplate.execute(new RedisCallback<List<CallersStatics>>() { public List<CallersStatics> doInRedis(RedisConnection connection) throws DataAccessException { String k = Constants.REDIS_SERVER_CALLER_PREFIX + serverIp + "_" + serviceId; StringRedisConnection conn = ((StringRedisConnection)connection); Set<StringTuple> callers = conn.zRangeByScoreWithScores(k, Long.MIN_VALUE, Long.MAX_VALUE); if (callers.isEmpty()){ return Collections.EMPTY_LIST; } List<CallersStatics> res = new ArrayList<CallersStatics>(); for (StringTuple tuple:callers){ Double score = tuple.getScore(); String value = tuple.getValueAsString(); CallersStatics statics = new CallersStatics(); statics.setTime(score.longValue()); statics.setCallers(JSON.parseObject(value, HashMap.class)); res.add(statics); } Collections.sort(res); return res; } }); }
@Override public void evict(Object key) { final String keyf = (String) key; redisTemplate.execute(new RedisCallback<Long>() { public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.del(keyf.getBytes()); } }); }
@Override public void clear() { redisTemplate.execute(new RedisCallback<String>() { public String doInRedis(RedisConnection connection) throws DataAccessException { connection.flushDb(); return "ok"; } }); }
@Before public void setUp() { template.execute(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { connection.flushDb(); return "FLUSHED"; } }); }
@Override public Boolean flushDB() { return redisTemplate.execute((RedisCallback<Boolean>) redisConnection -> { redisConnection.flushDb(); return redisConnection.dbSize() == 0; }); }
@Override public void clearGroup(final String groupName, final boolean containPkCache) { //清除缓存组的key String cacheGroupKey = groupName + CacheHandler.GROUPKEY_SUFFIX; Set<String> keys = stringRedisTemplate.opsForZSet().range(cacheGroupKey, 0, -1); if (keys.isEmpty()) { return; } final Object[] keysToArray = keys.toArray(new String[0]); redisTemplate.execute(new RedisCallback<Void>() { @Override public Void doInRedis(RedisConnection connection) throws DataAccessException { byte[][] keyArray = new byte[keysToArray.length][]; //先转成key的序列化格式 for (int i = 0; i < keyArray.length; i++) { keyArray[i] = keySerializer.serialize(keysToArray[i]); } connection.del(keyArray); logger.debug("cascade remove cache keyPattern:{},size:{}", cacheGroupKey, keysToArray.length); if (containPkCache) { //删除ID的缓存 String idKeyPattern = groupName + ".id:*"; Set<byte[]> idKeys = connection.keys(idKeyPattern.getBytes()); if (idKeys.size() > 0) { connection.del(idKeys.toArray(new byte[0][0])); logger.debug("cascade remove cache keyPattern:{},size:{}", idKeyPattern, idKeys.size()); } } return null; } }); stringRedisTemplate.opsForZSet().remove(cacheGroupKey, keysToArray); }
/** * 添加到带有 过期时间的 缓存 * * @param key redis主键 * @param value 值 * @param time 过期时间 */ public void setExpire(final byte[] key, final byte[] value, final long time) { redisTemplate.execute((RedisCallback<Long>) connection -> { connection.set(key, value); connection.expire(key, time); LOGGER.info("[redisTemplate redis]放入 缓存 url:{} ========缓存时间为{}秒", key, time); return 1L; }); }
/** * 添加到带有 过期时间的 缓存 * * @param key redis主键 * @param value 值 * @param time 过期时间 */ public void setExpire(final String key, final String value, final long time) { redisTemplate.execute((RedisCallback<Long>) connection -> { RedisSerializer<String> serializer = getRedisSerializer(); byte[] keys = serializer.serialize(key); byte[] values = serializer.serialize(value); connection.set(keys, values); connection.expire(keys, time); LOGGER.info("[redisTemplate redis]放入 缓存 url:{} ========缓存时间为{}秒", key, time); return 1L; }); }
/** * 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销 * * @param keys redis主键数组 * @param values 值数组 * @param time 过期时间 */ public void setExpire(final String[] keys, final String[] values, final long time) { redisTemplate.execute((RedisCallback<Long>) connection -> { RedisSerializer<String> serializer = getRedisSerializer(); for (int i = 0; i < keys.length; i++) { byte[] bKeys = serializer.serialize(keys[i]); byte[] bValues = serializer.serialize(values[i]); connection.set(bKeys, bValues); connection.expire(bKeys, time); LOGGER.info("[redisTemplate redis]放入 缓存 url:{} ========缓存时间为:{}秒", keys[i], time); } return 1L; }); }
/** * 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销 * * @param keys the keys * @param values the values */ public void set(final String[] keys, final String[] values) { redisTemplate.execute((RedisCallback<Long>) connection -> { RedisSerializer<String> serializer = getRedisSerializer(); for (int i = 0; i < keys.length; i++) { byte[] bKeys = serializer.serialize(keys[i]); byte[] bValues = serializer.serialize(values[i]); connection.set(bKeys, bValues); LOGGER.info("[redisTemplate redis]放入 缓存 url:{}", keys[i]); } return 1L; }); }
/** * 添加到缓存 * * @param key the key * @param value the value */ public void set(final String key, final String value) { redisTemplate.execute((RedisCallback<Long>) connection -> { RedisSerializer<String> serializer = getRedisSerializer(); byte[] keys = serializer.serialize(key); byte[] values = serializer.serialize(value); connection.set(keys, values); LOGGER.info("[redisTemplate redis]放入 缓存 url:{}", key); return 1L; }); }
/** * 查询在这个时间段内即将过期的key * * @param key the key * @param time the time * @return the list */ public List<String> willExpire(final String key, final long time) { final List<String> keysList = new ArrayList<>(); redisTemplate.execute((RedisCallback<List<String>>) connection -> { Set<String> keys = redisTemplate.keys(key + "*"); for (String key1 : keys) { Long ttl = connection.ttl(key1.getBytes(DEFAULT_CHARSET)); if (0 <= ttl && ttl <= 2 * time) { keysList.add(key1); } } return keysList; }); return keysList; }
/** * 根据key获取对象 * * @param key the key * @return the string */ public String get(final String key) { String resultStr = redisTemplate.execute((RedisCallback<String>) connection -> { RedisSerializer<String> serializer = getRedisSerializer(); byte[] keys = serializer.serialize(key); byte[] values = connection.get(keys); return serializer.deserialize(values); }); LOGGER.info("[redisTemplate redis]取出 缓存 url:{} ", key); return resultStr; }
/** * 清空redis存储的数据 * * @return the string */ public String flushDB() { return redisTemplate.execute((RedisCallback<String>) connection -> { connection.flushDb(); return "ok"; }); }
/** * 删除key * * @param keys the keys * @return the long */ public long del(final String... keys) { return redisTemplate.execute((RedisCallback<Long>) connection -> { long result = 0; for (String key : keys) { result = connection.del(key.getBytes(DEFAULT_CHARSET)); } return result; }); }
/** * 对某个主键对应的值加一,value值必须是全数字的字符串 * * @param key the key * @return the long */ public long incr(final String key) { return redisTemplate.execute((RedisCallback<Long>) connection -> { RedisSerializer<String> redisSerializer = getRedisSerializer(); return connection.incr(redisSerializer.serialize(key)); }); }
@Override public void clear() { getRedisTemplate().execute((RedisCallback) redisConnection -> { redisConnection.flushDb(); return null; }); }