org.springframework.data.redis.core.RedisCallback Java Examples
The following examples show how to use
org.springframework.data.redis.core.RedisCallback.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DataService.java From MyCommunity with Apache License 2.0 | 6 votes |
public long calculateDAU(Date start, Date end) { if (start == null || end == null) { throw new IllegalArgumentException("参数不能为空!"); } // 整理该日期范围内的key List<byte[]> keyList = new ArrayList<>(); Calendar calendar = Calendar.getInstance(); calendar.setTime(start); while (!calendar.getTime().after(end)) { String key = RedisKeyUtil.getDAUKey(df.format(calendar.getTime())); keyList.add(key.getBytes()); calendar.add(Calendar.DATE, 1); } // 进行OR运算 return (long) redisTemplate.execute(new RedisCallback() { @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { String redisKey = RedisKeyUtil.getDAUKey(df.format(start), df.format(end)); connection.bitOp(RedisStringCommands.BitOperation.OR, redisKey.getBytes(), keyList.toArray(new byte[0][0])); return connection.bitCount(redisKey.getBytes()); } }); }
Example #2
Source File: RedisDistributedLock.java From microservices-platform with Apache License 2.0 | 6 votes |
private boolean setRedis(final String key, final long expire) { try { boolean status = redisTemplate.execute((RedisCallback<Boolean>) connection -> { String uuid = UUID.randomUUID().toString(); lockFlag.set(uuid); byte[] keyByte = redisTemplate.getStringSerializer().serialize(key); byte[] uuidByte = redisTemplate.getStringSerializer().serialize(uuid); boolean result = connection.set(keyByte, uuidByte, Expiration.from(expire, TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.ifAbsent()); return result; }); return status; } catch (Exception e) { log.error("set redisDistributeLock occured an exception", e); } return false; }
Example #3
Source File: IValidateCodeServiceImpl.java From open-capacity-platform with Apache License 2.0 | 6 votes |
/** * 获取验证码 * @param deviceId * 前端唯一标识/手机号 */ @Override public String getCode(String deviceId) { String code = "" ; try { code = redisTemplate.execute(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { // redis info byte[] temp = "".getBytes(); temp = connection.get(buildKey(deviceId).getBytes()) ; connection.close(); return new String(temp); } }); } catch (Exception e) { throw new AuthenticationException("验证码不存在"){}; } return code ; }
Example #4
Source File: IValidateCodeServiceImpl.java From open-capacity-platform with Apache License 2.0 | 6 votes |
/** * 保存用户验证码,和randomStr绑定 * @param deviceId * 客户端生成 * @param imageCode * 验证码信息 */ @Override public void saveImageCode(String deviceId, String imageCode) { String text = imageCode.toLowerCase().toString(); redisTemplate.execute(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { // redis info connection.set(buildKey(deviceId).getBytes(), imageCode.getBytes()); connection.expire(buildKey(deviceId).getBytes(), 60*5); connection.close(); return ""; } }); }
Example #5
Source File: RedisDistributedLock.java From microservices-platform with Apache License 2.0 | 6 votes |
/** * 释放锁 * @param key 锁的key * @return 成功/失败 */ public boolean releaseLock(String key) { // 释放锁的时候,有可能因为持锁之后方法执行时间大于锁的有效期,此时有可能已经被另外一个线程持有锁,所以不能直接删除 try { // 使用lua脚本删除redis中匹配value的key,可以避免由于方法执行时间过长而redis锁自动过期失效的时候误删其他线程的锁 // spring自带的执行脚本方法中,集群模式直接抛出不支持执行脚本的异常,所以只能拿到原redis的connection来执行脚本 Boolean result = redisTemplate.execute((RedisCallback<Boolean>) connection -> { byte[] scriptByte = redisTemplate.getStringSerializer().serialize(UNLOCK_LUA); return connection.eval(scriptByte, ReturnType.BOOLEAN, 1 , redisTemplate.getStringSerializer().serialize(key) , redisTemplate.getStringSerializer().serialize(lockFlag.get())); }); return result; } catch (Exception e) { log.error("release redisDistributeLock occured an exception", e); } finally { lockFlag.remove(); } return false; }
Example #6
Source File: RedisAuthorizationCodeServices.java From cloud-service with MIT License | 6 votes |
@Override protected OAuth2Authentication remove(final String code) { OAuth2Authentication oAuth2Authentication = redisTemplate.execute(new RedisCallback<OAuth2Authentication>() { @Override public OAuth2Authentication doInRedis(RedisConnection connection) throws DataAccessException { byte[] keyByte = codeKey(code).getBytes(); byte[] valueByte = connection.get(keyByte); if (valueByte != null) { connection.del(keyByte); return SerializationUtils.deserialize(valueByte); } return null; } }); return oAuth2Authentication; }
Example #7
Source File: RedisController.java From open-capacity-platform with Apache License 2.0 | 6 votes |
@RequestMapping("/memoryInfo") @ResponseBody public String getMemoryInfo() { Map<String, Object> map = new HashMap<>(); Object o = redisTemplate.execute(new RedisCallback() { @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { return connection.info("memory").get("used_memory"); } }); map.put("used_memory", o); map.put("create_time", System.currentTimeMillis()); return JSON.toJSONString(map); }
Example #8
Source File: RedisRepository.java From SpringBoot2.0 with Apache License 2.0 | 6 votes |
/** * 根据key获取对象 * * @param keyPatten the key patten * @return the keys values */ public Map<String, Object> getKeysValues(final String keyPatten) { log.debug("[redisTemplate redis] getValues() patten={} ", keyPatten); return redisTemplate.execute((RedisCallback<Map<String, Object>>) connection -> { RedisSerializer<String> serializer = getRedisSerializer(); Map<String, Object> maps = new HashMap<>(16); Set<String> keys = redisTemplate.keys(keyPatten + "*"); if (!CollectionUtils.isEmpty(keys)) { for (String key : keys) { byte[] bKeys = serializer.serialize(key); byte[] bValues = connection.get(bKeys); Object value = OBJECT_SERIALIZER.deserialize(bValues); maps.put(key, value); } } return maps; }); }
Example #9
Source File: RedisRecordImporter.java From sofa-dashboard-client with Apache License 2.0 | 6 votes |
@Override public void addRecords(HostAndPort hostAndPort, List<StoreRecord> records) { template.executePipelined((RedisCallback<Void>) connection -> { for (StoreRecord record : records) { byte[] keyName = getKeyName(hostAndPort.toInstanceId(), record.getSchemeName()) .getBytes(Charset.defaultCharset()); byte[] value = JsonUtils.toJsonString(record) .getBytes(Charset.defaultCharset()); long score = record.getTimestamp(); long expire = score - timeoutTtl; connection.zRemRangeByScore(keyName, 0, expire); // Expire timeout record connection.zAdd(keyName, score, value); } return null; }); }
Example #10
Source File: RedisSmsVerificationCodeMismatchEventHandler.java From daming with Apache License 2.0 | 6 votes |
public void on(SmsVerificationCodeMismatchEvent event) { String key = toKey(event.getMobile(), event.getScope()); List<Object> attempts = redisTemplate.executePipelined((RedisCallback<Long>) connection -> { StringRedisConnection conn = (StringRedisConnection) connection; conn.sAdd(key, event.toString()); long expires = Duration.between(event.getWhen(), event.getExpiresAt()).getSeconds(); conn.expire(key, expires); conn.sCard(key); return null; }); log.debug("Got Redis pipeline {}", attempts.stream().map(Object::toString).collect(joining(DELIMITER))); if (attempts.size() == 3) { if (toAttempts(attempts) >= threshold) { log.info("Too many failure verification attempts for {} {}", event.getMobile(), event.getScope()); remove(key); domainEventPublisher.publish(new TooManyFailureSmsVerificationAttemptsEvent(UUID.randomUUID().toString(), clock.now(), event.getMobile(), event.getScope())); } } }
Example #11
Source File: RedisDistributedLock.java From SpringBoot2.0 with Apache License 2.0 | 6 votes |
private boolean setRedis(final String key, final long expire) { try { boolean status = redisTemplate.execute((RedisCallback<Boolean>) connection -> { String uuid = UUID.randomUUID().toString(); lockFlag.set(uuid); byte[] keyByte = redisTemplate.getStringSerializer().serialize(key); byte[] uuidByte = redisTemplate.getStringSerializer().serialize(uuid); boolean result = connection.set(keyByte, uuidByte, Expiration.from(expire, TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.ifAbsent()); return result; }); return status; } catch (Exception e) { log.error("set redisDistributeLock occured an exception", e); } return false; }
Example #12
Source File: TarocoRedisRepository.java From Taroco with Apache License 2.0 | 5 votes |
/** * 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销 * * @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); log.debug("[redisTemplate redis]放入 缓存 url:{} ========缓存时间为:{}秒", keys[i], time); } return 1L; }); }
Example #13
Source File: RedisCache.java From poseidon with Apache License 2.0 | 5 votes |
/** * Clears this cache instance */ @Override public void clear() { RedisTemplate redisTemplate = getRedisTemplate(); redisTemplate.execute((RedisCallback) connection -> { connection.flushDb(); return null; }); logger.debug("Clear all the cached query result from redis"); }
Example #14
Source File: SpringRedisGenericCache.java From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
@Override public void evict(String... keys) { for (String k : keys) { redisTemplate.execute((RedisCallback<Long>) redis -> { return redis.del(_key(k)); }); } }
Example #15
Source File: RedisLock.java From java-tutorial with MIT License | 5 votes |
/** * setNX * * @param key * @param value * @return */ public boolean setNX(final String key, final String value) { Object object = null; try { object = redisTemplate.execute((RedisCallback<Object>) redisConnection -> { StringRedisSerializer redisSerializer = new StringRedisSerializer(); Boolean success = redisConnection.setNX(Objects.requireNonNull(redisSerializer.serialize(key)), Objects.requireNonNull(redisSerializer.serialize(value))); redisConnection.close(); return success; }); } catch (Exception e) { logger.error("setNX redis error, key : {}", key); } return object != null ? (Boolean) object : false; }
Example #16
Source File: RedisServiceImpl.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
@Override public void delKey(final String key) { redisTemplate.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { redisTemplate.delete(key); return true; } }); }
Example #17
Source File: RedisRepository.java From SpringBoot2.0 with Apache License 2.0 | 5 votes |
/** * 查询在这个时间段内即将过期的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; }
Example #18
Source File: SpringRedisCache.java From J2Cache with Apache License 2.0 | 5 votes |
@Override public void setBytes(String key, byte[] bytes) { redisTemplate.opsForHash().getOperations().execute((RedisCallback<List<byte[]>>) redis -> { redis.set(_key(key).getBytes(), bytes); redis.hSet(region.getBytes(), key.getBytes(), bytes); return null; }); }
Example #19
Source File: RedisServiceImpl.java From mySpringBoot with Apache License 2.0 | 5 votes |
@Override public long del(final String key){ long result = redisTemplate.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); long value = connection.del(serializer.serialize(key)); return value; } }); return result; }
Example #20
Source File: SpringRedisGenericCache.java From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
@Override public void setBytes(String key, byte[] bytes, long timeToLiveInSeconds) { if (timeToLiveInSeconds <= 0) { log.debug(String.format("Invalid timeToLiveInSeconds value : %d , skipped it.", timeToLiveInSeconds)); setBytes(key, bytes); } else { redisTemplate.execute((RedisCallback<List<byte[]>>) redis -> { redis.setEx(_key(key), (int) timeToLiveInSeconds, bytes); return null; }); } }
Example #21
Source File: RedisServiceImpl.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
@Override public <T> T hGet(final String key, final String field, Class<T> clz) { return redisTemplate.execute(new RedisCallback<T>() { @Override public T doInRedis(RedisConnection connection) { RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); byte[] res = connection.hGet(serializer.serialize(key), serializer.serialize(field)); if (res != null && res.length > 0) { return JosnRedisUtil.toBean(serializer.deserialize(res), clz); } else { return null; } } }); }
Example #22
Source File: RedisRepository.java From SpringBoot2.0 with Apache License 2.0 | 5 votes |
/** * 根据key获取对象 * * @param key the key * @return the string */ public Object get(final String key) { Object resultStr = redisTemplate.execute((RedisCallback<Object>) connection -> { RedisSerializer<String> serializer = getRedisSerializer(); byte[] keys = serializer.serialize(key); byte[] values = connection.get(keys); return OBJECT_SERIALIZER.deserialize(values); }); log.debug("[redisTemplate redis]取出 缓存 url:{} ", key); return resultStr; }
Example #23
Source File: TarocoRedisRepository.java From Taroco with Apache License 2.0 | 5 votes |
/** * 清空redis存储的数据 * * @return the string */ public String flushDB() { return redisTemplate.execute((RedisCallback<String>) connection -> { connection.flushDb(); return "ok"; }); }
Example #24
Source File: TarocoRedisRepository.java From Taroco with Apache License 2.0 | 5 votes |
/** * 添加到缓存 * * @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); log.debug("[redisTemplate redis]放入 缓存 url:{}", key); return 1L; }); }
Example #25
Source File: RedisServiceImpl.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
@Override public long lpush(final String key, Object obj) { final String value = JosnRedisUtil.toJson(obj); long result = redisTemplate.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); long count = connection.lPush(serializer.serialize(key), serializer.serialize(value)); return count; } }); return result; }
Example #26
Source File: RedisServiceImpl.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
@Override public boolean exists(final String key) { Boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); return connection.exists(serializer.serialize(key)); } }); return result == null ? false : result; }
Example #27
Source File: RedisServiceImpl.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
@Override public Long incr(final String key) { Long result = redisTemplate.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); return connection.incr(serializer.serialize(key)); } }); return result; }
Example #28
Source File: RedisServiceImpl.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
@Override public String get(final String key) { String result = redisTemplate.execute(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); byte[] value = connection.get(serializer.serialize(key)); return serializer.deserialize(value); } }); return result; }
Example #29
Source File: RedisServiceImpl.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
@Override public boolean set(final String key, final String value) { boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); connection.set(serializer.serialize(key), serializer.serialize(value)); return true; } }); return result; }
Example #30
Source File: RedisCache.java From poseidon with Apache License 2.0 | 5 votes |
/** * Clears this cache instance */ @Override public void clear() { RedisTemplate redisTemplate = getRedisTemplate(); redisTemplate.execute((RedisCallback) connection -> { connection.flushDb(); return null; }); logger.debug("Clear all the cached query result from redis"); }