Java Code Examples for redis.clients.jedis.Jedis#close()

The following examples show how to use redis.clients.jedis.Jedis#close() . 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: WispKvStoreCodisKvImpl.java    From wisp with Apache License 2.0 6 votes vote down vote up
/**
 * @param tableId
 * @param key
 *
 * @return
 *
 * @throws WispProcessorException
 */
@Override
public String get(String tableId, String key) throws WispProcessorException {

    Jedis jedis = null;
    try {

        LOGGER.debug("jedis get: {} {}", tableId, key);

        jedis = jedisPool.getResource();

        String hKey = redisPrefix + tableId;
        return jedis.hget(hKey, key);

    } catch (Exception e) {

        throw new WispProcessorException(e);
    } finally {

        if (jedis != null) {
            jedis.close();
        }
    }
}
 
Example 2
Source File: RedisRegistry.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isAvailable() {
    for (JedisPool jedisPool : jedisPools.values()) {
        try {
            Jedis jedis = jedisPool.getResource();
            try {
                if (jedis.isConnected()) {
                    return true; // At least one single machine is available.
                }
            } finally {
                jedis.close();
            }
        } catch (Throwable t) {
        }
    }
    return false;
}
 
Example 3
Source File: RedisDAO.java    From jseckill with Apache License 2.0 6 votes vote down vote up
public Seckill getSeckill(long seckillId) {
    //redis操作逻辑
    try {
        Jedis jedis = jedisPool.getResource();
        try {
            String key = RedisKeyPrefix.SECKILL_GOODS + seckillId;
            byte[] bytes = jedis.get(key.getBytes());
            //缓存中获取到bytes
            if (bytes != null) {
                //空对象
                Seckill seckill = schema.newMessage();
                ProtostuffIOUtil.mergeFrom(bytes, seckill, schema);
                //seckill 被反序列化
                return seckill;
            }
        } finally {
            jedis.close();
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
 
Example 4
Source File: JedisSentinelTest.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Test
public void sentinelSet() {
  Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());

  try {
    Map<String, String> parameterMap = new HashMap<String, String>();
    parameterMap.put("down-after-milliseconds", String.valueOf(1234));
    parameterMap.put("parallel-syncs", String.valueOf(3));
    parameterMap.put("quorum", String.valueOf(2));
    j.sentinelSet(MASTER_NAME, parameterMap);

    List<Map<String, String>> masters = j.sentinelMasters();
    for (Map<String, String> master : masters) {
      if (master.get("name").equals(MASTER_NAME)) {
        assertEquals(1234, Integer.parseInt(master.get("down-after-milliseconds")));
        assertEquals(3, Integer.parseInt(master.get("parallel-syncs")));
        assertEquals(2, Integer.parseInt(master.get("quorum")));
      }
    }

    parameterMap.put("quorum", String.valueOf(1));
    j.sentinelSet(MASTER_NAME, parameterMap);
  } finally {
    j.close();
  }
}
 
Example 5
Source File: JedisStream.java    From RedisDirectory with Apache License 2.0 6 votes vote down vote up
@Override
public void rename(String fileLengthKey, String fileDataKey, String oldField, String newField, List<byte[]> values, long
        fileLength) {
    Jedis jedis = openJedis();
    Pipeline pipelined = jedis.pipelined();
    //add new file length
    pipelined.hset(fileLengthKey.getBytes(), newField.getBytes(), Longs.toByteArray(fileLength));
    //add new file content
    Long blockSize = getBlockSize(fileLength);
    for (int i = 0; i < blockSize; i++) {
        pipelined.hset(fileDataKey.getBytes(), getBlockName(newField, i), compressFilter(values.get(i)));
    }
    pipelined.sync();
    jedis.close();
    values.clear();
    deleteFile(fileLengthKey, fileDataKey, oldField, blockSize);
}
 
Example 6
Source File: JedisClusterPipeline.java    From AutoLoadCache with Apache License 2.0 5 votes vote down vote up
@Override
public void close() {
    clean();
    clients.clear();
    for (Jedis jedis : jedisMap.values()) {
        flushCachedData(jedis);
        jedis.close();
    }
    jedisMap.clear();
}
 
Example 7
Source File: RedisUtil.java    From zheng with MIT License 5 votes vote down vote up
/**
 * 设置 byte[] 过期时间
 * @param key
 * @param value
 * @param seconds 以秒为单位
 */
public synchronized static void set(byte[] key, byte[] value, int seconds) {
	try {
		Jedis jedis = getJedis();
		jedis.set(key, value);
		jedis.expire(key, seconds);
		jedis.close();
	} catch (Exception e) {
		LOGGER.error("Set key error : " + e);
	}
}
 
Example 8
Source File: RedisDeployCenterImpl.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
private String getConfigValue(long appId, String host, int port, String key) {
    Jedis jedis = redisCenter.getJedis(appId, host, port, Protocol.DEFAULT_TIMEOUT * 3, Protocol.DEFAULT_TIMEOUT * 3);
    try {
        List<String> values = jedis.configGet(key);
        if (values == null || values.size() < 1) {
            return null;
        }
        return values.get(1);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        jedis.close();
    }
}
 
Example 9
Source File: RedisActionHistory.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Override
public void addFullAction(String clientName, Action a) throws APIException {

	JedisPool pool = poolManager.get(clientName);
	if (pool != null)
	{
		Jedis jedis = null;
		try 
		{
			ActionLogEntry al = new ActionLogEntry(clientName,a);
			String val = mapper.writeValueAsString(al);
			String key = MemCacheKeys.getActionFullHistory(clientName, a.getUserId());
			jedis = pool.getResource();
			jedis.zadd(key, a.getDate().getTime()/1000, val);
			//zremrangebyscore needed
		}
		catch (JsonProcessingException e) 
		{
			logger.error("Failed to convert action to json ",e);
		}
		finally
		{
			if (jedis != null)
			{
				jedis.close();
			}
		}
	}
	else
	{
		logger.error("No redis pool found for "+clientName);
	}
}
 
Example 10
Source File: JedisPoolTest.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
@Test
public void customClientName() {
  JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), hnp.getPort(), 2000,
      "foobared", 0, "my_shiny_client_name");

  Jedis jedis = pool0.getResource();

  assertEquals("my_shiny_client_name", jedis.clientGetname());

  jedis.close();
  pool0.destroy();
  assertTrue(pool0.isClosed());
}
 
Example 11
Source File: JedisClientPool.java    From paas with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean exists(String key) {
    Jedis jedis = jedisPool.getResource();
    Boolean result = jedis.exists(key);
    jedis.close();
    return result;
}
 
Example 12
Source File: JedisCglibProxy.java    From limiter with MIT License 5 votes vote down vote up
@Override
public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
    Jedis jedis = null;
    init();
    try {
        jedis = getJedis();
        return method.invoke(jedis, args);
    } finally {
        if (null != jedis) {
            jedis.close();
        }
    }
}
 
Example 13
Source File: JedisClientPool.java    From paas with Apache License 2.0 5 votes vote down vote up
@Override
public String srandmember(String key) {
    Jedis jedis = jedisPool.getResource();
    String result = jedis.srandmember(key);
    jedis.close();
    return result;
}
 
Example 14
Source File: MappingCache.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
public static Mapping getMapping(String key) {
    Jedis redis = null;
    try {
        redis = getJedis();
        Object obj = SerializeUtil.unserialize(redis.get((DomainContant.COMMON_DOMAIN + key + _SUFFIX_MAPPING).getBytes()));
        if (obj instanceof Mapping) {
            return (Mapping) obj;
        }
    } finally {
        if (redis != null) {
            redis.close();
        }
    }
    return null;
}
 
Example 15
Source File: SeckillServiceImpl.java    From jseckill with Apache License 2.0 4 votes vote down vote up
/**
 * @param seckillId
 * @param userPhone
 * @param md5
 * @return
 * @throws SeckillException
 * @TODO 先在redis里处理,然后发送到mq,最后减库存到数据库
 */
private SeckillExecution handleSeckillAsync(long seckillId, long userPhone, String md5)
        throws SeckillException {
    if (md5 == null || !md5.equals(getMD5(seckillId))) {
        // 遇到黑客攻击,检测到了数据篡改
        logger.info("seckill_DATA_REWRITE!!!. seckillId={},userPhone={}", seckillId, userPhone);
        throw new SeckillException(SeckillStateEnum.DATA_REWRITE);
    }

    long threadId = Thread.currentThread().getId();

    Jedis jedis = jedisPool.getResource();
    String inventoryKey = RedisKeyPrefix.SECKILL_INVENTORY + seckillId;
    String boughtKey = RedisKeyPrefix.BOUGHT_USERS + seckillId;

    String inventoryStr = jedis.get(inventoryKey);
    int inventory = Integer.valueOf(inventoryStr);
    if (inventory <= 0) {
        jedis.close();
        logger.info("SECKILLSOLD_OUT. seckillId={},userPhone={}", seckillId, userPhone);
        throw new SeckillException(SeckillStateEnum.SOLD_OUT);
    }
    if (jedis.sismember(boughtKey, String.valueOf(userPhone))) {
        jedis.close();
        //重复秒杀
        logger.info("SECKILL_REPEATED. seckillId={},userPhone={}", seckillId, userPhone);
        throw new SeckillException(SeckillStateEnum.REPEAT_KILL);
    } else {
        jedis.close();

        // 进入待秒杀队列,进行后续串行操作
        SeckillMsgBody msgBody = new SeckillMsgBody();
        msgBody.setSeckillId(seckillId);
        msgBody.setUserPhone(userPhone);
        mqProducer.send(msgBody);

        // 立即返回给客户端,说明秒杀成功了
        PayOrder payOrder = new PayOrder();
        payOrder.setUserPhone(userPhone);
        payOrder.setSeckillId(seckillId);
        payOrder.setState(SeckillStateEnum.ENQUEUE_PRE_SECKILL.getState());
        logger.info("ENQUEUE_PRE_SECKILL>>>seckillId={},userPhone={}", seckillId, userPhone);
        return new SeckillExecution(seckillId, SeckillStateEnum.ENQUEUE_PRE_SECKILL, payOrder);
    }
}
 
Example 16
Source File: RedisIsolationPersistenceInspector.java    From cachecloud with Apache License 2.0 4 votes vote down vote up
@Override
public boolean inspect(Map<InspectParamEnum, Object> paramMap) {
    final String host = MapUtils.getString(paramMap, InspectParamEnum.SPLIT_KEY);
    List<InstanceInfo> list = (List<InstanceInfo>) paramMap.get(InspectParamEnum.INSTANCE_LIST);
    outer:
    for (InstanceInfo info : list) {
        final int port = info.getPort();
        final int type = info.getType();
        final long appId = info.getAppId();
        int status = info.getStatus();
        //非正常节点
        if (status != InstanceStatusEnum.GOOD_STATUS.getStatus()) {
            continue;
        }
        if (TypeUtil.isRedisDataType(type)) {
            Jedis jedis = redisCenter.getJedis(appId, host, port, REDIS_DEFAULT_TIME, REDIS_DEFAULT_TIME);
            try {
                Map<String, String> persistenceMap = parseMap(jedis);
                if (persistenceMap.isEmpty()) {
                    logger.error("{}:{} get persistenceMap failed", host, port);
                    continue;
                }
                if (!isAofEnabled(persistenceMap)) {
                    continue;
                }
                long aofCurrentSize = MapUtils.getLongValue(persistenceMap, RedisInfoEnum.aof_current_size.getValue());
                long aofBaseSize = MapUtils.getLongValue(persistenceMap, RedisInfoEnum.aof_base_size.getValue());
                //阀值大于60%
                long aofThresholdSize = (long) (aofBaseSize * 1.6);
                double percentage = getPercentage(aofCurrentSize, aofBaseSize);
                if (aofCurrentSize >= aofThresholdSize
                        //大于64Mb
                        && aofCurrentSize > (64 * 1024 * 1024)) {
                    //bgRewriteAof
                    boolean isInvoke = invokeBgRewriteAof(jedis);
                    if (!isInvoke) {
                        logger.error("{}:{} invokeBgRewriteAof failed", host, port);
                        continue;
                    } else {
                        logger.warn("{}:{} invokeBgRewriteAof started percentage={}", host, port, percentage);
                    }
                    while (true) {
                        try {
                            //before wait 1s
                            TimeUnit.SECONDS.sleep(1);
                            Map<String, String> loopMap = parseMap(jedis);
                            Integer aofRewriteInProgress = MapUtils.getInteger(loopMap, "aof_rewrite_in_progress", null);
                            if (aofRewriteInProgress == null) {
                                logger.error("loop watch:{}:{} return failed", host, port);
                                break;
                            } else if (aofRewriteInProgress <= 0) {
                                //bgrewriteaof Done
                                logger.warn("{}:{} bgrewriteaof Done lastSize:{}Mb,currentSize:{}Mb", host, port, getMb(aofCurrentSize), getMb(MapUtils.getLongValue(loopMap, "aof_current_size")));
                                break;
                            } else {
                                //wait 1s
                                TimeUnit.SECONDS.sleep(1);
                            }
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                } else {
                    if (percentage > 50D) {
                        long currentSize = getMb(aofCurrentSize);
                        logger.info("checked {}:{} aof increase percentage:{}% currentSize:{}Mb", host, port, percentage, currentSize > 0 ? currentSize : "<1");
                    }
                }
            } finally {
                jedis.close();
            }
        }
    }
    return true;
}
 
Example 17
Source File: RedisClient.java    From flycache with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param jedis
 */
private static void closeJedis(Jedis jedis) {
    if (jedis != null) {
        jedis.close();
    }
}
 
Example 18
Source File: AbstractPayManager.java    From pay-spring-boot with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 获取一个新的<b>支付订单号</b>(注意<b>业务订单号</b>和<b>支付订单号</b>的概念区别!项目中所有的商户订单号均为支付订单号)
 * 
 * <p>格式定义:</p>
 * 
 * <pre>
 * 固定16位。
 * 假设<b>支付订单号</b>为:00ba00ix1sob0001
 * 
 * +------------------------------------+------------------+----------------+------------------------+--------------------+---------------------+----------------------------------+
 * | 00                                 | b                | a              | 0                      | 0                  | ix1sob              | 0001                             |
 * +------------------------------------+------------------+----------------+------------------------+--------------------+---------------------+----------------------------------+
 * | 从2017年起至现在的年数,32进制表示                      | 月份,32进制表示             | 日,32进制表示           | 订单号类型,32进制表示                | 保留位,32进制表示              | 用户唯一id,固定6位              | 该用户当日创建订单数量,32进制表示                    |
 * +------------------------------------+------------------+----------------+------------------------+--------------------+---------------------+----------------------------------+
 * </pre>
 * 
 * @param uuid 用户唯一id
 * 
 * @return 支付订单号
 */
public String newTradeNo(String uuid){
    Jedis redis = null;
    try {
        redis = CommonConfig.getJedisPool().getResource();
        StringBuilder builder = new StringBuilder(16);
        Date date = new Date();
        
        String key = TRADE_COUNT_KEY_TMPL.replace("{type}", getTradeType())
                                         .replace("{uuid}", uuid);
        int count = redis.incr(key).intValue();
        if(count == 1){
            int ttl = (int)((PayDateUtil.getIntegralEndTime(date).getTime() - date.getTime())/1000l);
            redis.expire(key, ttl);
        }
        
        int year = Integer.parseInt(PayDateUtil.format(date, "yyyy"));
        year = year - 2017;
        int month = Integer.parseInt(PayDateUtil.format(date, "MM"));
        if(month > 9){
            month = month + 87;
        }else{
            month = month + 48;
        }
        int day = Integer.parseInt(PayDateUtil.format(date, "dd"));
        if(day > 9){
            day = day + 87;
        }else{
            day = day + 48;
        }
        builder.append(StringUtils.leftPad(Integer.toString(year, 32), 2, "0"));
        builder.append((char) month);
        builder.append((char) day);
        
        /**
         * 类型
         */
        builder.append(getTradeType());
        
        /**
         * 保留位
         */
        builder.append(0);
        
        /**
         * 用户唯一id
         */
        builder.append(uuid);
        
        /**
         * 数量
         */
        builder.append(StringUtils.leftPad(Integer.toString(count, 32), 4, "0"));
        
        return builder.toString();
    } finally {
        if(redis != null){
            redis.close();
            redis = null;
        }
    }
}
 
Example 19
Source File: WxQrcodePay.java    From pay-spring-boot with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 预支付
 * @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 20
Source File: JedisUtil.java    From Project with Apache License 2.0 3 votes vote down vote up
/**
 * 合并多个集合并返回合并后的结果,合并后的结果集合并不保存<br/>
 * 
 * @param keys
 * @return 合并后的结果集合
 * @see
 */
public Set<String> sunion(String... keys) {
	Jedis jedis = getJedis();
	Set<String> set = jedis.sunion(keys);
	jedis.close();
	return set;
}