package com.tiantu.spark.hdp import redis.clients.jedis.{Jedis, JedisPool, JedisPoolConfig} /** * TODO * * @author hell * @date2020/12/25 15:46 * */ object RedisUtil { @volatile private var jedisPool: JedisPool = null /** * 获取JedisPool 实例 */ def getResource() = { if (jedisPool == null) { synchronized( if (jedisPool == null) { val config = new JedisPoolConfig config.setMaxTotal(5) config.setMaxIdle(2) config.setMaxWaitMillis(3000) jedisPool = new JedisPool(config, "192.168.0.90", 6379); } ) } jedisPool.getResource } /** * 释放JedisPool 连接资源 * * @param jedis */ def returnResource(jedis: Jedis) = { if (jedis != null) jedis.close() } /** * 原子计数器 * * @param key * @param step * @return */ def incrBy(key: String, step: Long): Long = { val jedis = getResource() val count = jedis.incrBy(key, step) returnResource(jedis) count } /** * 通过key找到value */ def getRedsis(key: String): String = { val redis = getResource() val str = redis.get(key) RedisUtil.returnResource(redis) str } /** * 存储key-value */ def setRedsis(key: String, value: String): Unit = { val redis = getResource() redis.set(key, value.toString) RedisUtil.returnResource(redis) } }