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

The following examples show how to use redis.clients.jedis.Jedis#get() . 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: JedisUtil.java    From newblog with Apache License 2.0 6 votes vote down vote up
public String get(String key) {
    Jedis jedis = null;
    String result = "";
    try {
        jedis = getJedis();
        if (jedis != null) {
            result = jedis.get(key);
        } else {
            logger.error("get opt connection null error!");
        }
    } catch (JedisConnectionException e) {
        if (jedis != null) {
            jedis.close();
            jedis = null;
        }
        logger.error("get value connect error:", e);
    } finally {
        returnJedisResource(jedis);
    }
    return result;
}
 
Example 2
Source File: HandlerImpl.java    From tephra with MIT License 6 votes vote down vote up
private <T> T get(String key, boolean remove) {
    Jedis jedis = pool.getResource();
    byte[] k = key.getBytes();
    byte[] bytes = jedis.get(k);
    if (validator.isEmpty(bytes)) {
        jedis.close();

        return null;
    }

    if (remove)
        jedis.del(k);
    T t = unserialize(jedis, k, bytes);
    jedis.close();

    return t;
}
 
Example 3
Source File: RedisPoolUtilBAK.java    From mmall20180107 with Apache License 2.0 6 votes vote down vote up
public static String get(String key){

        Jedis jedis = null;
        String result = null;

        try {
            jedis = RedisPool.getJedis();
            result = jedis.get(key);
        } catch (Exception e) {
            log.error("get key:{}  error",key,e);
            RedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        }


        RedisPool.returnResource(jedis);

        return result;

    }
 
Example 4
Source File: GetSetBenchmark.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws UnknownHostException, IOException {
  Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort());
  jedis.connect();
  jedis.auth("foobared");
  jedis.flushAll();

  long begin = Calendar.getInstance().getTimeInMillis();

  for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
    String key = "foo" + n;
    jedis.set(key, "bar" + n);
    jedis.get(key);
  }

  long elapsed = Calendar.getInstance().getTimeInMillis() - begin;

  jedis.disconnect();

  System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
}
 
Example 5
Source File: RedisSinkBolt.java    From jstorm with Apache License 2.0 6 votes vote down vote up
private byte[] retryGet(byte[] key) {
    int retry = 0;
    byte[] ret;
    while (true) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            ret = jedis.get(key);
            return ret;
        } catch (JedisConnectionException e) {
            if (jedis != null) {
                pool.returnBrokenResource(jedis);
                jedis = null;
            }
            if (retry > retryLimit) {
                throw e;
            }
            retry++;
        } finally {
            if (jedis != null) {
                pool.returnResource(jedis);
            }
        }
    }
}
 
Example 6
Source File: RedisClient.java    From flycache with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 通过key获取储存在redis中的value
 * </p>
 * <p>
 * 并释放连接
 * </p>
 *
 * @param key
 * @return 成功返回value 失败返回null
 */
public String get(String key) {
    Jedis jedis = null;
    String value = null;
    try {
        jedis = jedisPool.getResource();
        value = jedis.get(key);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        closeJedis(jedis);
    }
    return value;
}
 
Example 7
Source File: M2H.java    From BigData with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws SQLException, URISyntaxException, IOException {
	fileSystem = getInstance();
	// 从mysql中读取更新的数据,返回ResultSet
	Jedis jedis = new Jedis("192.168.1.107", 6379);
	String num = jedis.get("mark");
	jedis.close();
	int count = 0;
	if (num != null) {
		count = Integer.parseInt(num);
	}
	String sql = "select * from test1 limit ?,99999999";

	// 处理mysql to hdfs
	queryRS(sql, count);
}
 
Example 8
Source File: JedisDemo.java    From JavaTutorial with Apache License 2.0 5 votes vote down vote up
/**
 * 单机单连接方式。
 */
private static void single() {
    Jedis client = new Jedis("192.168.56.102", 6379);
    String result = client.set("key-string", "Hello, Redis!");
    System.out.println( String.format("set指令执行结果:%s", result) );
    String value = client.get("key-string");
    System.out.println( String.format("get指令执行结果:%s", value) );
}
 
Example 9
Source File: JedisClient.java    From belling-redis-id-generator with Apache License 2.0 5 votes vote down vote up
/**
 * @Description 
 * 
 * @author butterfly
 * @param key
 * @return
 * @throws Exception
 */
public String get(String key) throws Exception {
	Jedis jedis = null;
	try {
		jedis = jedisPool.getResource();
		return jedis.get(key);
	} catch (Exception ex) {
		throw ex;
	} finally {
		// 返还到连接池
		if (null != jedis)
			jedis.close();
	}
}
 
Example 10
Source File: RedisManager.java    From jee-universal-bms with Apache License 2.0 5 votes vote down vote up
/**
 * 通过key获取储存在redis中的value
 * 并释放连接
 * @param key
 * @return 成功返回value 失败返回null
 */
public String get(String key) {
    Jedis jedis = null;
    String value = null;
    try {
        jedis = pool.getResource();
        value = jedis.get(key);
    } catch (Exception e) {
        pool.returnBrokenResource(jedis);
        e.printStackTrace();
    } finally {
        returnResource(pool, jedis);
    }
    return value;
}
 
Example 11
Source File: CommonCache.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 获取值(用户ID)
 *
 * @returne
 */
public static String getAndRemoveValue(String key) {
    Jedis redis = null;
    String value = "";
    try {
        redis = getJedis();
        value = redis.get(key);
        removeValue(key);
    } finally {
        if (redis != null) {
            redis.close();
        }
    }
    return value;
}
 
Example 12
Source File: RedisPoolUtil.java    From redis-distributed-lock with Apache License 2.0 5 votes vote down vote up
public static String get(String key){
    Jedis jedis = null;
    String result = null;
    try {
        jedis = RedisPool.getJedis();
        result = jedis.get(key);
    } catch (Exception e){
        e.printStackTrace();
    } finally {
        if (jedis != null) {
            jedis.close();
        }
        return result;
    }
}
 
Example 13
Source File: RedisStore.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public LookupValue get(Pair<String, DataType> pair) {
  Jedis jedis = pool.getResource();
  LookupValue values;

  // check the type
  DataType type = pair.getRight();
  String key = pair.getLeft();
  switch (type) {
    case STRING:
      values = new LookupValue(jedis.get(key), type);
      break;
    case LIST:
      values = new LookupValue(jedis.lrange(key, 0, jedis.llen(key)), type);
      break;
    case HASH:
      values = new LookupValue(jedis.hgetAll(key), type);
      break;
    case SET:
      values = new LookupValue(jedis.smembers(key), type);
      break;
    default:
      values = null;
  }
  jedis.close();

  return values;
}
 
Example 14
Source File: JedisCacheService.java    From springbootexamples with Apache License 2.0 5 votes vote down vote up
/**
 * 获取缓存中的对象
 * @param key
 * @return
 */
public Object getObject(String key) {
    Jedis jedis = null;
    Object object = null;
    try {
        jedis = jedisPool.getResource();
        byte[] ObjectByteArray = jedis.get(key.getBytes());
        object = unserialize(ObjectByteArray);
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        close(jedis);
    }
    return object;
}
 
Example 15
Source File: JWTCache.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 获取值(用户ID)
 * @returne
 */
public static String getValue(String jdi){
    Jedis redis = null;
    try {
        redis = getJedis();
        return redis.get(jdi);
    }finally {
        if(redis != null){
            redis.close();
        }
    }
}
 
Example 16
Source File: JedisTest.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
@Test
public void connectWithShardInfo() {
  JedisShardInfo shardInfo = new JedisShardInfo("localhost", Protocol.DEFAULT_PORT);
  shardInfo.setPassword("foobared");
  Jedis jedis = new Jedis(shardInfo);
  jedis.get("foo");
}
 
Example 17
Source File: UrlUtil.java    From BigData with GNU General Public License v3.0 5 votes vote down vote up
public static void juageUrl(String userHref) {
	// 用户url去重
	String md5 = MD5Filter.md5(userHref);
	Jedis jedis = JedisUtil.getJedis();
	if (jedis.get(md5) == null) {
		jedis.append(md5, "md5url");
		jedis.lpush(JedisUtil.urlkey, userHref);
		JedisUtil.returnResource(jedis);
	} else {
		JedisUtil.returnResource(jedis);
	}
}
 
Example 18
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 19
Source File: WxMobilePay.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 prepayidKey = "pay:wx:out_trade_no:".concat(trade.getOutTradeNo()).concat(":prepay_id");

        /**
         * 从缓存中寻找预支付id
         */
        String reply = redis.get(prepayidKey);
        if(StringUtils.isNotBlank(reply)){
            return reply;
        }

        /**
         * 远程请求预支付id
         */
        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("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 prepayIdElement = responseDoc.getRootElement().element("prepay_id");
        if(prepayIdElement == null){
            throw new RuntimeException("请求预支付未找到预支付id(prepay_id)");
        }
        String prepayid = prepayIdElement.getTextTrim();

        log.info("[微信支付]成功获取预支付id[" + prepayid + "]");

        /**
         * 缓存预支付id
         */
        redis.set(prepayidKey, prepayid);
        redis.expire(prepayidKey, 7170);

        return prepayid;
    }finally{
        if(redis != null){
            redis.close();
            redis = null;
        }
    }
}
 
Example 20
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);
    }

    Jedis jedis = jedisPool.getResource();
    String inventoryKey = RedisKeyPrefix.SECKILL_INVENTORY + seckillId;
    if (jedis.sismember(RedisKey.SECKILLED_USER, String.valueOf(userPhone))) {
        //重复秒杀
        logger.info("seckill REPEATED. seckillId={},userPhone={}", seckillId, userPhone);
        throw new SeckillException(SeckillStateEnum.REPEAT_KILL);
    } else {
        String inventoryStr = jedis.get(inventoryKey);
        int inventory = Integer.valueOf(inventoryStr);
        if (inventory <= 0) {
            throw new SeckillException(SeckillStateEnum.SOLD_OUT);
        }
        jedis.watch(inventoryKey);
        Transaction tx = jedis.multi();
        tx.decr(inventoryKey);
        tx.sadd(RedisKey.SECKILLED_USER, String.valueOf(userPhone));
        List<Object> resultList = tx.exec();
        jedis.unwatch();
        if (resultList != null && resultList.size() == 2) {
            // 秒杀成功,后面异步更新到数据库中
            // 发送消息到消息队列
            SeckillMsgBody msgBody = new SeckillMsgBody();
            msgBody.setSeckillId(seckillId);
            msgBody.setUserPhone(userPhone);
            mqProducer.send(JSON.toJSONString(msgBody));

            // 立即返回给客户端,说明秒杀成功了
            SuccessKilled successKilled = new SuccessKilled();
            successKilled.setUserPhone(userPhone);
            successKilled.setSeckillId(seckillId);
            successKilled.setState(SeckillStateEnum.SUCCESS.getState());
            return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
        } else {
            throw new SeckillException(SeckillStateEnum.RUSH_FAILED);
        }
    }
}