Java Code Examples for redis.clients.jedis.Jedis#expire()
The following examples show how to use
redis.clients.jedis.Jedis#expire() .
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: RGTRedisService.java From redis-game-transaction with Apache License 2.0 | 6 votes |
@Override public String getString(String key, int seconds){ Jedis jedis = null; boolean sucess = true; String rt = null; try { jedis = jedisPool.getResource(); rt = jedis.get(key); if(seconds > -1){ jedis.expire(key, seconds); } } catch (Exception e) { sucess = false; returnBrokenResource(jedis, "getString", e); } finally { if (sucess && jedis != null) { returnResource(jedis); } } return rt; }
Example 2
Source File: JedisUtils.java From Shop-for-JavaWeb with MIT License | 6 votes |
/** * 设置List缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static long setObjectList(String key, List<Object> value, int cacheSeconds) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { jedis.del(key); } List<byte[]> list = Lists.newArrayList(); for (Object o : value){ list.add(toBytes(o)); } result = jedis.rpush(getBytesKey(key), (byte[][])list.toArray()); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setObjectList {} = {}", key, value); } catch (Exception e) { logger.warn("setObjectList {} = {}", key, value, e); } finally { returnResource(jedis); } return result; }
Example 3
Source File: JedisUtil.java From scaffold-cloud with MIT License | 6 votes |
/** * 设置Map缓存 * * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static String setMap(String key, Map<String, String> value, int cacheSeconds) { String result = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { jedis.del(key); } result = jedis.hmset(key, value); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } } catch (Exception e) { logger.warn("setMap {} = {}", key, value, e); } finally { close(jedis); } return result; }
Example 4
Source File: RedisContainer.java From bahir-flink with Apache License 2.0 | 6 votes |
@Override public void incrByEx(String key, Long value, Integer ttl) { Jedis jedis = null; try { jedis = getInstance(); jedis.incrBy(key, value); if (ttl != null) { jedis.expire(key, ttl); } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Cannot send Redis with incrby command with increment {} with ttl {} error message {}", key, value, ttl, e.getMessage()); } throw e; } finally { releaseInstance(jedis); } }
Example 5
Source File: CacheServiceRedisImpl.java From redis_util with Apache License 2.0 | 6 votes |
public boolean expire(String key, int expireSecond) { log.trace("strar set expire " + key); Jedis jedis = null; try { jedis = redisConnection.getJedis(); jedis.select(dbIndex); return jedis.expire(key, expireSecond) == 1; } catch (Exception e) { log.warn(e.getMessage(), e); } finally { if (jedis != null) { jedis.close(); } } return false; }
Example 6
Source File: RedisManager.java From jee-universal-bms with Apache License 2.0 | 6 votes |
/** * set * @param key * @param value * @param expire * @return */ public byte[] set(byte[] key, byte[] value, int expire) { Jedis jedis = pool.getResource(); try { jedis.set(key, value); if (expire != 0) { jedis.expire(key, expire); } } catch (Exception e) { pool.returnBrokenResource(jedis); e.printStackTrace(); } finally { pool.returnResource(jedis); } return value; }
Example 7
Source File: JedisUtils.java From easyweb with Apache License 2.0 | 6 votes |
/** * 设置Set缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static long setSet(String key, Set<String> value, int cacheSeconds) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { jedis.del(key); } result = jedis.sadd(key, (String[])value.toArray()); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setSet {} = {}", key, value); } catch (Exception e) { logger.warn("setSet {} = {}", key, value, e); } finally { returnResource(jedis); } return result; }
Example 8
Source File: JedisUtil.java From scaffold-cloud with MIT License | 6 votes |
/** * 设置缓存 useDefaultSerializable=true 使用jdk方式序列化 * * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static String setObject( String key, Object value, int cacheSeconds, boolean useDefaultSerializable) { String result = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { jedis.del(key); } result = jedis.set(getBytesKey(key), toBytes(value, useDefaultSerializable)); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } } catch (Exception e) { logger.warn("setObject {} = {}", key, value, e); } finally { close(jedis); } return result; }
Example 9
Source File: RedisCacheProvider.java From xiaoyaoji with GNU General Public License v3.0 | 6 votes |
private String hget(String token, String key, int expire) { if (key == null) return null; Jedis jedis = null; try { jedis = pool.getResource(); String rs = jedis.hget(token, key); if (rs != null) { jedis.expire(token, expire); } return rs; } finally { if (jedis != null) { jedis.close(); } } }
Example 10
Source File: UUIDServiceRedisImpl.java From redis_util with Apache License 2.0 | 6 votes |
public Long fetchDailyUUID(String key, Integer length, Boolean haveDay) { Jedis jedis = null; try { jedis = redisConnection.getJedis(); jedis.select(dbIndex); Calendar now = new GregorianCalendar(); String day = df.format(now.getTime()); key = key + "_" + day; Long num = jedis.incr(key); //设置 key 过期时间 if (num == 1) { jedis.expire(key, (24 - now.get(Calendar.HOUR_OF_DAY)) * 3600 + 1800); } if (haveDay) { return createUUID(num, day, length); } else { return num; } } finally { if (jedis != null) { jedis.close(); } } }
Example 11
Source File: JedisUtil.java From scaffold-cloud with MIT License | 6 votes |
/** * 设置Set缓存 * * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static long setSet(String key, Set<String> value, int cacheSeconds) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { jedis.del(key); } result = jedis.sadd(key, value.toArray(new String[value.size()])); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } } catch (Exception e) { logger.warn("setSet {} = {}", key, value, e); } finally { close(jedis); } return result; }
Example 12
Source File: LockTest.java From code with Apache License 2.0 | 5 votes |
/** * 尝试获取分布式锁 * @param jedis Redis客户端 * @param lockKey 锁 * @param requestId 请求标识 * @param expireTime 超期时间 */ public static void wrongGetLock1(Jedis jedis, String lockKey, String requestId, int expireTime) { Long result = jedis.setnx(lockKey, requestId); if (result == 1) { // 若在这里程序突然崩溃,则无法设置过期时间,将发生死锁 jedis.expire(lockKey, expireTime); } }
Example 13
Source File: JedisUtil.java From Project with Apache License 2.0 | 5 votes |
/** * 设置过期时间 * * @param key * @param seconds */ public void expire(String key, int seconds) { if (seconds <= 0) { return; } Jedis jedis = getJedis(); jedis.expire(key, seconds); jedis.close(); }
Example 14
Source File: JedisUtil.java From BigData with GNU General Public License v3.0 | 5 votes |
/** * 设置过期时间 * * @author ruan 2013-4-11 * @param key * @param seconds */ public void expire(String key, int seconds) { if (seconds <= 0) { return; } Jedis jedis = getJedis(); jedis.expire(key, seconds); returnJedis(jedis); }
Example 15
Source File: AuthorizationInterceptor.java From token-authentication-example with Apache License 2.0 | 4 votes |
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (!(handler instanceof HandlerMethod)) { return true; } HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); // 如果打上了AuthToken注解则需要验证token if (method.getAnnotation(AuthToken.class) != null || handlerMethod.getBeanType().getAnnotation(AuthToken.class) != null) { String token = request.getHeader(httpHeaderName); log.info("token is {}", token); String username = ""; Jedis jedis = new Jedis("localhost", 6379); if (token != null && token.length() != 0) { username = jedis.get(token); log.info("username is {}", username); } if (username != null && !username.trim().equals("")) { //log.info("token birth time is: {}",jedis.get(username+token)); Long tokeBirthTime = Long.valueOf(jedis.get(token + username)); log.info("token Birth time is: {}", tokeBirthTime); Long diff = System.currentTimeMillis() - tokeBirthTime; log.info("token is exist : {} ms", diff); if (diff > ConstantKit.TOKEN_RESET_TIME) { jedis.expire(username, ConstantKit.TOKEN_EXPIRE_TIME); jedis.expire(token, ConstantKit.TOKEN_EXPIRE_TIME); log.info("Reset expire time success!"); Long newBirthTime = System.currentTimeMillis(); jedis.set(token + username, newBirthTime.toString()); } //用完关闭 jedis.close(); request.setAttribute(REQUEST_CURRENT_KEY, username); return true; } else { JSONObject jsonObject = new JSONObject(); PrintWriter out = null; try { response.setStatus(unauthorizedErrorCode); response.setContentType(MediaType.APPLICATION_JSON_VALUE); jsonObject.put("code", ((HttpServletResponse) response).getStatus()); jsonObject.put("message", HttpStatus.UNAUTHORIZED); out = response.getWriter(); out.println(jsonObject); return false; } catch (Exception e) { e.printStackTrace(); } finally { if (null != out) { out.flush(); out.close(); } } } } request.setAttribute(REQUEST_CURRENT_KEY, null); return true; }
Example 16
Source File: WxWebMobilePay.java From pay-spring-boot with GNU General Public License v3.0 | 4 votes |
/** * 预支付 * @param trade * @return * @throws DocumentException */ private String prepay(WxTrade trade) throws DocumentException { Jedis redis = null; try{ redis = CommonConfig.getJedisPool().getResource(); String codeUrlKey = "pay:wx:out_trade_no:".concat(trade.getOutTradeNo()).concat(":code_url"); /** * 从缓存中寻找二维码链接 */ String reply = redis.get(codeUrlKey); if(StringUtils.isNotBlank(reply)){ return reply; } /** * 远程请求二维码链接 */ log.info("[微信支付]开始预支付"); Map<String, String> params = new HashMap<String, String>(); params.put("appid", trade.getAppid()); params.put("mch_id", trade.getMchid()); params.put("nonce_str", trade.getNonceStr()); params.put("body", trade.getBody()); params.put("detail", trade.getDetail()); params.put("out_trade_no", trade.getOutTradeNo()); params.put("total_fee", trade.getTotalFee()); params.put("spbill_create_ip", trade.getSpbillCreateIp()); params.put("notify_url", trade.getNotifyUrl()); params.put("trade_type", trade.getTradeType()); params.put("scene_info", trade.getSceneInfo()); params.put("sign", signMD5(params)); log.info("[微信支付]预支付参数构造完成\n" + JSON.toJSONString(params)); Document paramsDoc = buildDocFromMap(params); log.info("[微信支付]预支付XML参数构造完成\n" + paramsDoc.asXML()); log.info("[微信支付]开始请求微信服务器进行预支付"); SimpleResponse response = HttpClient.getClient().post(WxPayConfig.getUnifiedorderURL(), paramsDoc.asXML()); if(response.getCode() != 200){ throw new RuntimeException("请求预支付通信失败, HTTP STATUS[" + response.getCode() + "]"); } String responseBody = response.getStringBody(); log.info("[微信支付]预支付通信成功\n" + responseBody); /** * 解析响应数据 */ Document responseDoc = DocumentHelper.parseText(responseBody); Element mwebUrlElement = responseDoc.getRootElement().element("mweb_url"); if(mwebUrlElement == null){ throw new RuntimeException("请求预支付未找到付款链接(mweb_url)"); } String mwebUrl = mwebUrlElement.getTextTrim(); log.info("[微信支付]成功获取付款链接[" + mwebUrl + "]"); /** * 缓存二维码链接 */ redis.set(codeUrlKey, mwebUrl); redis.expire(codeUrlKey, 7170); return mwebUrl; }finally{ if(redis != null){ redis.close(); redis = null; } } }
Example 17
Source File: WxQrcodePay.java From pay-spring-boot with GNU General Public License v3.0 | 4 votes |
/** * 预支付 * @param trade * @return * @throws DocumentException */ private String prepay(WxTrade trade) throws DocumentException { Jedis redis = null; try{ redis = CommonConfig.getJedisPool().getResource(); String codeUrlKey = "pay:wx:out_trade_no:".concat(trade.getOutTradeNo()).concat(":code_url"); /** * 从缓存中寻找二维码链接 */ String reply = redis.get(codeUrlKey); if(StringUtils.isNotBlank(reply)){ return reply; } /** * 远程请求二维码链接 */ log.info("[微信支付]开始预支付"); Map<String, String> params = new HashMap<String, String>(); params.put("appid", trade.getAppid()); params.put("mch_id", trade.getMchid()); params.put("nonce_str", trade.getNonceStr()); params.put("body", trade.getBody()); params.put("detail", trade.getDetail()); params.put("out_trade_no", trade.getOutTradeNo()); params.put("total_fee", trade.getTotalFee()); params.put("spbill_create_ip", trade.getSpbillCreateIp()); params.put("notify_url", trade.getNotifyUrl()); params.put("trade_type", trade.getTradeType()); params.put("product_id", trade.getProductId()); params.put("sign", signMD5(params)); log.info("[微信支付]预支付参数构造完成\n" + JSON.toJSONString(params)); Document paramsDoc = buildDocFromMap(params); log.info("[微信支付]预支付XML参数构造完成\n" + paramsDoc.asXML()); log.info("[微信支付]开始请求微信服务器进行预支付"); SimpleResponse response = HttpClient.getClient().post(WxPayConfig.getUnifiedorderURL(), paramsDoc.asXML()); if(response.getCode() != 200){ throw new RuntimeException("请求预支付通信失败, HTTP STATUS[" + response.getCode() + "]"); } String responseBody = response.getStringBody(); log.info("[微信支付]预支付通信成功\n" + responseBody); /** * 解析响应数据 */ Document responseDoc = DocumentHelper.parseText(responseBody); Element codeUrlElement = responseDoc.getRootElement().element("code_url"); if(codeUrlElement == null){ throw new RuntimeException("请求预支付未找到二维码链接(code_url)"); } String codeUrl = codeUrlElement.getTextTrim(); log.info("[微信支付]成功获取二维码链接[" + codeUrl + "]"); /** * 缓存二维码链接 */ redis.set(codeUrlKey, codeUrl); redis.expire(codeUrlKey, 7170); return codeUrl; }finally{ if(redis != null){ redis.close(); redis = null; } } }
Example 18
Source File: JedisSessionDAO.java From NutzSite with Apache License 2.0 | 4 votes |
@Override public void update(Session session) throws UnknownSessionException { if (session == null || session.getId() == null) { return; } HttpServletRequest request = Mvcs.getReq(); if (request != null){ String uri = request.getServletPath(); // 如果是静态文件,则不更新SESSION if (isStaticFile(uri)){ return; } // 手动控制不更新SESSION // if (Global.NO.equals(request.getParameter("updateSession"))){ // return; // } } Jedis jedis = null; try { jedis = jedisAgent.getResource(); // 获取登录者编号 PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY); String principalId = pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY; jedis.hset(sessionKeyPrefix, session.getId().toString(), principalId + "|" + session.getTimeout() + "|" + session.getLastAccessTime().getTime()); jedis.set(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()), JedisUtils.toBytes(session)); // 设置超期时间 int timeoutSeconds = (int)(session.getTimeout() / 1000); jedis.expire((sessionKeyPrefix + session.getId()), timeoutSeconds); logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : ""); } catch (Exception e) { logger.error("update {} {}", session.getId(), request != null ? request.getRequestURI() : "", e); } finally { Streams.safeClose(jedis); } }
Example 19
Source File: ObjectCacheOperate.java From xian with Apache License 2.0 | 4 votes |
public static long expire(Jedis jedis, String key, int seconds) { return jedis.expire(key, seconds); }
Example 20
Source File: JedisUtil.java From BigData with GNU General Public License v3.0 | 3 votes |
/** * 设置key的过期时间,以秒为单位 * * @param String * key * @param 时间 * ,已秒为单位 * @return 影响的记录数 * */ public long expired(String key, int seconds) { Jedis jedis = getJedis(); long count = jedis.expire(key, seconds); returnJedis(jedis); return count; }