Redis缓存对象相关
2018-01-06 18:22
253 查看
1、想要使用redis先获得连接池对象,及JedisPool
然后在配置生成连接池对象需要的参数咯
(1)你可以写一个参数实体类,再写一个bean注入到spring
(2)可以直接在开启springmvc配置注解,直接配置
代码如下
这样连接池对象就能获得了,然后就可以用里面的方法了。
2、
(1)用@Service管理起来直接使用,为了方便key值管理,定义一个key前缀接口
以后所有key都继承这个base基类就好了,定义自己的key前缀和过期时间
然后定义一些基础方法,方便业务使用
这里json处理用的fastjson
使用时直接调用接口方法就好了,注意数据库修改时及时同步缓存一致
(2)自己封装个工具类
这个工具类功能几乎很全了,举个栗子
然后在配置生成连接池对象需要的参数咯
(1)你可以写一个参数实体类,再写一个bean注入到spring
@Component @ConfigurationProperties(prefix="redis")//这个在properties的配置文件里噢,框架是springboot,表示前缀是redis的,参数名称得对应。 public class RedisConfig { private String host; private int port; private int timeout;//秒 private String password; private int poolMaxTotal; private int poolMaxIdle; private int poolMaxWait;//秒 public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getPoolMaxTotal() { return poolMaxTotal; } public void setPoolMaxTotal(int poolMaxTotal) { this.poolMaxTotal = poolMaxTotal; } public int getPoolMaxIdle() { return poolMaxIdle; } public void setPoolMaxIdle(int poolMaxIdle) { this.poolMaxIdle = poolMaxIdle; } public int getPoolMaxWait() { return poolMaxWait; } public void setPoolMaxWait(int poolMaxWait) { this.poolMaxWait = poolMaxWait; } }
@Service public class RedisPoolFactory { @Autowired RedisConfig redisConfig; @Bean public JedisPool JedisPoolFactory() { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle()); poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal()); poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000); JedisPool jp = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getTimeout()*1000, redisConfig.getPassword(), 0); return jp; } }
(2)可以直接在开启springmvc配置注解,直接配置
代码如下
/** * 强指定redis的JedisPool接口构造函数,这样才能在centos成功创建jedispool **/ public class JedisPoolWriper { /** Redis连接池对象 */ private JedisPool jedisPool; public JedisPoolWriper(final JedisPoolConfig poolConfig, final String host, final int port) { try { jedisPool = new JedisPool(poolConfig, host, port); } catch (Exception e) { e.printStackTrace(); } } /** * 获取Redis连接池对象 * @return */ public JedisPool getJedisPool() { return jedisPool; } /** * 注入Redis连接池对象 * @param jedisPool */ public void setJedisPool(JedisPool jedisPool) { this.jedisPool = jedisPool; } }
** * Ma.li.ran * 2017/11/17 0017 15:51 * redis配置 */ @Configuration public class RedisConfiguration { @Value("${redis.hostname}") private String hostname; @Value("${redis.port}") private int port; @Value("${redis.pool.maxActive}") private int maxTotal; @Value("${redis.pool.maxIdle}") private int maxIdle; @Value("${redis.pool.maxWait}") private long maxWaitMillis; @Value("${redis.pool.testOnBorrow}") private boolean testOnBorrow; @Autowired private JedisPoolConfig jedisPoolConfig; @Autowired private JedisPoolWriper jedisPoolWriper; @Autowired private JedisUtil jedisUtil; /** * 创建redis连接池的设置 */ @Bean(name = "jedisPoolConfig") public JedisPoolConfig createJedisConfig() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); //控制一个pool可分配多少个jedis实例 jedisPoolConfig.setMaxTotal(maxTotal); /* 连接池中最多可空闲maxIdle个连接,这里取值为20,表示即使没有数据库连接依然可以空闲20个随时等待待命 */ jedisPoolConfig.setMaxIdle(maxIdle); //最大等待时间,当没有可用链接时,连接池等待的最大归还时间,超出 1c140 抛出异常 jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); //在获取连接时检查有效性 jedisPoolConfig.setTestOnBorrow(testOnBorrow); return jedisPoolConfig; } /** * 创建redis连接池 */ @Bean(name = "jedisPool") public JedisPoolWriper createJedisPoolWriper() { JedisPoolWriper jedisPoolWriper = new JedisPoolWriper(jedisPoolConfig, hostname, port); return jedisPoolWriper; } /** * keys * @return */ @Bean(name = "jedisKeys") public JedisUtil.Keys createJedisKeys() { JedisUtil.Keys jedisKeys = jedisUtil.new Keys(); return jedisKeys; } /** * Strings * @return */ @Bean(name = "jedisStrings") public JedisUtil.Strings createJedisStrings() { JedisUtil.Strings jedisStrings= jedisUtil.new Strings(); return jedisStrings; } /** * Hash * @return */ @Bean(name = "jedisHash") public JedisUtil.Hash createJedisHash() { JedisUtil.Hash jedisHash= jedisUtil.new Hash(); return jedisHash; } /** * Lists * @return */ @Bean(name = "jedisLists") public JedisUtil.Lists createJedisLists() { JedisUtil.Lists jedisLists= jedisUtil.new Lists(); return jedisLists; } /** * Sets * @return */ @Bean(name = "jedisSets") public JedisUtil.Sets createJedisSets() { JedisUtil.Sets jedisSets= jedisUtil.new Sets(); return jedisSets; } }
这样连接池对象就能获得了,然后就可以用里面的方法了。
2、
(1)用@Service管理起来直接使用,为了方便key值管理,定义一个key前缀接口
public interface KeyPrefix { public int expireSeconds();//过期时间 public String getPrefix();//前缀 }
public abstract class BasePrefix implements KeyPrefix{ private int expireSeconds; private String prefix; public BasePrefix(String prefix) {//0代表永不过期 this(0, prefix); } public BasePrefix( int expireSeconds, String prefix) { this.expireSeconds = expireSeconds; this.prefix = prefix; } public int expireSeconds() {//默认0代表永不过期 return expireSeconds; } public String getPrefix() { String className = getClass().getSimpleName(); return className+":" + prefix; } }
以后所有key都继承这个base基类就好了,定义自己的key前缀和过期时间
然后定义一些基础方法,方便业务使用
这里json处理用的fastjson
@Service public class RedisService { @Autowired JedisPool jedisPool; /** * 获取当个对象 * */ public <T> T get(KeyPrefix prefix, String key, Class<T> clazz) { Jedis jedis = null; try { jedis = jedisPool.getResource(); //生成真正的key String realKey = prefix.getPrefix() + key; String str = jedis.get(realKey); T t = stringToBean(str, clazz); return t; }finally { returnToPool(jedis); } } /** * 设置对象 * */ public <T> boolean set(KeyPrefix prefix, String key, T value) { Jedis jedis = null; try { jedis = jedisPool.getResource(); String str = beanToString(value); if(str == null || str.length() <= 0) { return false; } //生成真正的key String realKey = prefix.getPrefix() + key; int seconds = prefix.expireSeconds(); if(seconds <= 0) { jedis.set(realKey, str); }else { jedis.setex(realKey, seconds, str); } return true; }finally { returnToPool(jedis); } } /** * 判断key是否存在 * */ public <T> boolean exists(KeyPrefix prefix, String key) { Jedis jedis = null; try { jedis = jedisPool.getResource(); //生成真正的key String realKey = prefix.getPrefix() + key; return jedis.exists(realKey); }finally { returnToPool(jedis); } } /** * 删除 * */ public boolean delete(KeyPrefix prefix, String key) { Jedis jedis = null; try { jedis = jedisPool.getResource(); //生成真正的key String realKey = prefix.getPrefix() + key; long ret = jedis.del(realKey); return ret > 0; }finally { returnToPool(jedis); } } /** * 增加值 * */ public <T> Long incr(KeyPrefix prefix, String key) { Jedis jedis = null; try { jedis = jedisPool.getResource(); //生成真正的key String realKey = prefix.getPrefix() + key; return jedis.incr(realKey); }finally { returnToPool(jedis); } } /** * 减少值 * */ public <T> Long decr(KeyPrefix prefix, String key) { Jedis jedis = null; try { jedis = jedisPool.getResource(); //生成真正的key String realKey = prefix.getPrefix() + key; return jedis.decr(realKey); }finally { returnToPool(jedis); } } public boolean delete(KeyPrefix prefix) { if(prefix == null) { return false; } List<String> keys = scanKeys(prefix.getPrefix()); if(keys==null || keys.size() <= 0) { return true; } Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.del(keys.toArray(new String[0])); return true; } catch (final Exception e) { e.printStackTrace(); return false; } finally { if(jedis != null) { jedis.close(); } } } public List<String> scanKeys(String key) { Jedis jedis = null; try { jedis = jedisPool.getResource(); List<String> keys = new ArrayList<String>(); String cursor = "0"; ScanParams sp = new ScanParams(); sp.match("*"+key+"*"); sp.count(100); do{ ScanResult<String> ret = jedis.scan(cursor, sp); List<String> result = ret.getResult(); if(result!=null && result.size() > 0){ keys.addAll(result); } //再处理cursor cursor = ret.getStringCursor(); }while(!cursor.equals("0")); return keys; } finally { if (jedis != null) { jedis.close(); } } } public static <T> String beanToString(T value) { if(value == null) { return null; } Class<?> clazz = value.getClass(); if(clazz == int.class || clazz == Integer.class) { return ""+value; }else if(clazz == String.class) { return (String)value; }else if(clazz == long.class || clazz == Long.class) { return ""+value; }else { return JSON.toJSONString(value); } } @SuppressWarnings("unchecked") public static <T> T stringToBean(String str, Class<T> clazz) { if(str == null || str.length() <= 0 || clazz == null) { return null; } if(clazz == int.class || clazz == Integer.class) { return (T)Integer.valueOf(str); }else if(clazz == String.class) { return (T)str; }else if(clazz == long.class || clazz == Long.class) { return (T)Long.valueOf(str); }else { return JSON.toJavaObject(JSON.parseObject(str), clazz); } } private void returnToPool(Jedis jedis) { if(jedis != null) { jedis.close(); } } }
使用时直接调用接口方法就好了,注意数据库修改时及时同步缓存一致
(2)自己封装个工具类
package com.maqway.wxht.controller.cache; import java.util.List; import java.util.Map; import java.util.Set; import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.SortingParams; import redis.clients.util.SafeEncoder; public class JedisUtil { /** * 缓存生存时间 */ private final int expire = 60000; /** * 操作Key的方法 */ public Keys KEYS; /** * 对存储结构为String类型的操作 */ public Strings STRINGS; /** * 对存储结构为List类型的操作 */ public Lists LISTS; /** * 对存储结构为Set类型的操作 */ public Sets SETS; /** * 对存储结构为HashMap类型的操作 */ public Hash HASH; /** * Redis连接池对象 */ private JedisPool jedisPool; /** * 获取redis连接池 */ public JedisPool getJedisPool() { return jedisPool; } /** * 设置redis连接池 */ public void setJedisPool(JedisPoolWriper jedisPoolWriper) { this.jedisPool = jedisPoolWriper.getJedisPool(); } /** * 从jedis连接池中获取获取jedis对象 */ public Jedis getJedis() { return jedisPool.getResource(); } /** * 设置过期时间 * * @author xiangze */ public void expire(String key, int seconds) { if (seconds <= 0) { return; } Jedis jedis = getJedis(); jedis.expire(key, seconds); jedis.close(); } /** * 设置默认过期时间 * * @author xiangze */ public void expire(String key) { expire(key, expire); } // *******************************************Keys*******************************************// public class Keys { public Keys() { } /** * 清空所有key */ public String flushAll() { Jedis jedis = getJedis(); String stata = jedis.flushAll(); jedis.close(); return stata; } /** * 更改key * * @return 状态码 */ public String rename(String oldkey, String newkey) { return rename(SafeEncoder.encode(oldkey), SafeEncoder.encode(newkey)); } /** * 更改key,仅当新key不存在时才执行 * * @return 状态码 */ public long renamenx(String oldkey, String newkey) { Jedis jedis = getJedis(); long status = jedis.renamenx(oldkey, newkey); jedis.close(); return status; } /** * 更改key * * @return 状态码 */ public String rename(byte[] oldkey, byte[] newkey) { Jedis jedis = getJedis(); String status = jedis.rename(oldkey, newkey); jedis.close(); return status; } /** * 设置key的过期时间,以秒为单位 * * */ public long expired(String key, int seconds) { Jedis jedis = getJedis(); long count = jedis.expire(key, seconds); jedis.close(); return count; } /** * 设置key的过期时间,它是距历元(即格林威治标准时间 1970 年 1 月 1 日的 00:00:00,格里高利历)的偏移量。 * * * */ public long expireAt(String key, long timestamp) { Jedis jedis = getJedis(); long count = jedis.expireAt(key, timestamp); jedis.close(); return count; } /** * 查询key的过期时间 * * @param key * @return 以秒为单位的时间表示 */ public long ttl(String key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); long len = sjedis.ttl(key); sjedis.close(); return len; } /** * 取消对key过期时间的设置 * * @return 影响的记录数 */ public long persist(String key) { Jedis jedis = getJedis(); long count = jedis.persist(key); jedis.close(); return count; } /** * 删除keys对应的记录,可以是多个key * * @param keys * @return 删除的记录数 */ public long del(String... keys) { Jedis jedis = getJedis(); long count = jedis.del(keys); jedis.close(); return count; } /** * 删除keys对应的记录,可以是多个key * * @param keys * @return 删除的记录数 */ public long del(byte[]... keys) { Jedis jedis = getJedis(); long count = jedis.del(keys); jedis.close(); return count; } /** * 判断key是否存在 * * @param key * @return boolean */ public boolean exists(String key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); boolean exis = sjedis.exists(key); sjedis.close(); return exis; } /** * 对List,Set,SortSet进行排序,如果集合数据较大应避免使用这个方法 * * @param key * @return List<String> 集合的全部记录 **/ public List<String> sort(String key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); List<String> list = sjedis.sort(key); sjedis.close(); return list; } /** * 对List,Set,SortSet进行排序或limit * * @param key * @param parame 定义排序类型或limit的起止位置. * @return List<String> 全部或部分记录 **/ public List<String> sort(String key, SortingParams parame) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); List<String> list = sjedis.sort(key, parame); sjedis.close(); return list; } /** * 返回指定key存储的类型 * * @param key * @return String string|list|set|zset|hash **/ public String type(String key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); String type = sjedis.type(key); sjedis.close(); return type; } /** * 查找所有匹配给定的模式的键 * * @param pattern key的表达式,*表示多个,?表示一个 */ public Set<String> keys(String pattern) { Jedis jedis = getJedis(); Set<String> set = jedis.keys(pattern); jedis.close(); return set; } } // *******************************************Strings*******************************************// public class Strings { public Strings() { } /** * 根据key获取记录 * * @param key * @return 值 */ public String get(String key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); String value = sjedis.get(key); sjedis.close(); return value; } /** * 根据key获取记录 * * @param key * @return 值 */ public byte[] get(byte[] key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); byte[] value = sjedis.get(key); sjedis.close(); return value; } /** * 添加记录,如果记录已存在将覆盖原有的value * * @param key * @param value * @return 状态码 */ public String set(String key, String value) { return set(SafeEncoder.encode(key), SafeEncoder.encode(value)); } /** * 添加记录,如果记录已存在将覆盖原有的value * * @param key * @param value * @return 状态码 */ public String set(String key, byte[] value) { return set(SafeEncoder.encode(key), value); } /** * 添加记录,如果记录已存在将覆盖原有的value * * @param key * @param value * @return 状态码 */ public String set(byte[] key, byte[] value) { Jedis jedis = getJedis(); String status = jedis.set(key, value); jedis.close(); return status; } /** * 添加有过期时间的记录 * * @param key * @param seconds 过期时间,以秒为单位 * @param value * @return String 操作状态 */ public String setEx(String key, int seconds, String value) { Jedis jedis = getJedis(); String str = jedis.setex(key, seconds, value); jedis.close(); return str; } /** * 添加有过期时间的记录 * * @param key * @param seconds 过期时间,以秒为单位 * @param value * @return String 操作状态 */ public String setEx(byte[] key, int seconds, byte[] value) { Jedis jedis = getJedis(); String str = jedis.setex(key, seconds, value); jedis.close(); return str; } /** * 添加一条记录,仅当给定的key不存在时才插入 * * @param key * @param value * @return long 状态码,1插入成功且key不存在,0未插入,key存在 */ public long setnx(String key, String value) { Jedis jedis = getJedis(); long str = jedis.setnx(key, value); jedis.close(); return str; } /** * 从指定位置开始插入数据,插入的数据会覆盖指定位置以后的数据<br/> * 例:String str1="123456789";<br/> * 对str1操作后setRange(key,4,0000),str1="123400009"; * * @param key * @param offset * @param value * @return long value的长度 */ public long setRange(String key, long offset, String value) { Jedis jedis = getJedis(); long len = jedis.setrange(key, offset, value); jedis.close(); return len; } /** * 在指定的key中追加value * * @param key * @param value * @return long 追加后value的长度 **/ public long append(String key, String value) { Jedis jedis = getJedis(); long len = jedis.append(key, value); jedis.close(); return len; } /** * 将key对应的value减去指定的值,只有value可以转为数字时该方法才可用 * * @param key * @param number 要减去的值 * @return long 减指定值后的值 */ public long decrBy(String key, long number) { Jedis jedis = getJedis(); long len = jedis.decrBy(key, number); jedis.close(); return len; } /** * <b>可以作为获取唯一id的方法</b><br/> * 将key对应的value加上指定的值,只有value可以转为数字时该方法才可用 * * @param key * @param number 要减去的值 * @return long 相加后的值 */ public long incrBy(String key, long number) { Jedis jedis = getJedis(); long len = jedis.incrBy(key, number); jedis.close(); return len; } /** * 对指定key对应的value进行截取 * * @param key * @param startOffset 开始位置(包含) * @param endOffset 结束位置(包含) * @return String 截取的值 */ public String getrange(String key, long startOffset, long endOffset) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); String value = sjedis.getrange(key, startOffset, endOffset); sjedis.close(); return value; } /** * 获取并设置指定key对应的value<br/> * 如果key存在返回之前的value,否则返回null * * @param key * @param value * @return String 原始value或null */ public String getSet(String key, String value) { Jedis jedis = getJedis(); String str = jedis.getSet(key, value); jedis.close(); return str; } /** * 批量获取记录,如果指定的key不存在返回List的对应位置将是null * * @param keys * @return List<String> 值得集合 */ public List<String> mget(String... keys) { Jedis jedis = getJedis(); List<String> str = jedis.mget(keys); jedis.close(); return str; } /** * 批量存储记录 * * @param keysvalues 例:keysvalues="key1","value1","key2","value2"; * @return String 状态码 */ public String mset(String... keysvalues) { Jedis jedis = getJedis(); String str = jedis.mset(keysvalues); jedis.close(); return str; } /** * 获取key对应的值的长度 * * @param key * @return value值得长度 */ public long strlen(String key) { Jedis jedis = getJedis(); long len = jedis.strlen(key); jedis.close(); return len; } } // *******************************************Sets*******************************************// public class Sets { public Sets() { } /** * 向Set添加一条记录,如果member已存在返回0,否则返回1 * * @param key * @param member * @return 操作码, 0或1 */ public long sadd(String key, String member) { Jedis jedis = getJedis(); long s = jedis.sadd(key, member); jedis.close(); return s; } public long sadd(byte[] key, byte[] member) { Jedis jedis = getJedis(); long s = jedis.sadd(key, member); jedis.close(); return s; } /** * 获取给定key中元素个数 * * @param key * @return 元素个数 */ public long scard(String key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); long len = sjedis.scard(key); sjedis.close(); return len; } /** * 返回从第一组和所有的给定集合之间的差异的成员 * * @param keys * @return 差异的成员集合 */ public Set<String> sdiff(String... keys) { Jedis jedis = getJedis(); Set<String> set = jedis.sdiff(keys); jedis.close(); return set; } /** * 这个命令等于sdiff,但返回的不是结果集,而是将结果集存储在新的集合中,如果目标已存在,则覆盖。 * * @param newkey 新结果集的key * @param keys 比较的集合 * @return 新集合中的记录数 **/ public long sdiffstore(String newkey, String... keys) { Jedis jedis = getJedis(); long s = jedis.sdiffstore(newkey, keys); jedis.close(); return s; } /** * 返回给定集合交集的成员,如果其中一个集合为不存在或为空,则返回空Set * * @param keys * @return 交集成员的集合 **/ public Set<String> sinter(String... keys) { Jedis jedis = getJedis(); Set<String> set = jedis.sinter(keys); jedis.close(); return set; } /** * 这个命令等于sinter,但返回的不是结果集,而是将结果集存储在新的集合中,如果目标已存在,则覆盖。 * * @param newkey 新结果集的key * @param keys 比较的集合 * @return 新集合中的记录数 **/ public long sinterstore(String newkey, String... keys) { Jedis jedis = getJedis(); long s = jedis.sinterstore(newkey, keys); jedis.close(); return s; } /** * 确定一个给定的值是否存在 * * @param key * @param member 要判断的值 * @return 存在返回1,不存在返回0 **/ public boolean sismember(String key, String member) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); boolean s = sjedis.sismember(key, member); sjedis.close(); return s; } /** * 返回集合中的所有成员 * * @param key * @return 成员集合 */ public Set<String> smembers(String key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); Set<String> set = sjedis.smembers(key); sjedis.close(); return set; } public Set<byte[]> smembers(byte[] key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); Set<byte[]> set = sjedis.smembers(key); sjedis.close(); return set; } /** * 将成员从源集合移出放入目标集合 <br/> * 如果源集合不存在或不包哈指定成员,不进行任何操作,返回0<br/> * 否则该成员从源集合上删除,并添加到目标集合,如果目标集合中成员已存在,则只在源集合进行删除 * * @param srckey 源集合 * @param dstkey 目标集合 * @param member 源集合中的成员 * @return 状态码,1成功,0失败 */ public long smove(String srckey, String dstkey, String member) { Jedis jedis = getJedis(); long s = jedis.smove(srckey, dstkey, member); jedis.close(); return s; } /** * 从集合中删除成员 * * @param key * @return 被删除的成员 */ public String spop(String key) { Jedis jedis = getJedis(); String s = jedis.spop(key); jedis.close(); return s; } /** * 从集合中删除指定成员 * * @param key * @param member 要删除的成员 * @return 状态码,成功返回1,成员不存在返回0 */ public long srem(String key, String member) { Jedis jedis = getJedis(); long s = jedis.srem(key, member); jedis.close(); return s; } /** * 合并多个集合并返回合并后的结果,合并后的结果集合并不保存<br/> * * @param keys * @return 合并后的结果集合 * @see */ public Set<String> sunion(String... keys) { Jedis jedis = getJedis(); Set<String> set = jedis.sunion(keys); jedis.close(); return set; } /** * 合并多个集合并将合并后的结果集保存在指定的新集合中,如果新集合已经存在则覆盖 * * @param newkey 新集合的key * @param keys 要合并的集合 **/ public long sunionstore(String newkey, String... keys) { Jedis jedis = getJedis(); long s = jedis.sunionstore(newkey, keys); jedis.close(); return s; } } // *******************************************Hash*******************************************// public class Hash { public Hash() { } /** * 从hash中删除指定的存储 * * @param key * @param fieid 存储的名字 * @return 状态码,1成功,0失败 */ public long hdel(String key, String fieid) { Jedis jedis = getJedis(); long s = jedis.hdel(key, fieid); jedis.close(); return s; } public long hdel(String key) { Jedis jedis = getJedis(); long s = jedis.del(key); jedis.close(); return s; } /** * 测试hash中指定的存储是否存在 * * @param key * @param fieid 存储的名字 * @return 1存在,0不存在 */ public boolean hexists(String key, String fieid) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); boolean s = sjedis.hexists(key, fieid); sjedis.close(); return s; } /** * 返回hash中指定存储位置的值 * * @param key * @param fieid 存储的名字 * @return 存储对应的值 */ public String hget(String key, String fieid) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); String s = sjedis.hget(key, fieid); sjedis.close(); return s; } public byte[] hget(byte[] key, byte[] fieid) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); byte[] s = sjedis.hget(key, fieid); sjedis.close(); return s; } /** * 以Map的形式返回hash中的存储和值 * * @param key * @return Map<Strinig,String> */ public Map<String, String> hgetAll(String key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); Map<String, String> map = sjedis.hgetAll(key); sjedis.close(); return map; } /** * 添加一个对应关系 * * @param key * @param fieid * @param value * @return 状态码 1成功,0失败,fieid已存在将更新,也返回0 **/ public long hset(String key, String fieid, String value) { Jedis jedis = getJedis(); long s = jedis.hset(key, fieid, value); jedis.close(); return s; } public long hset(String key, String fieid, byte[] value) { Jedis jedis = getJedis(); long s = jedis.hset(key.getBytes(), fieid.getBytes(), value); jedis.close(); return s; } /** * 添加对应关系,只有在fieid不存在时才执行 * * @param key * @param fieid * @param value * @return 状态码 1成功,0失败fieid已存 **/ public long hsetnx(String key, String fieid, String value) { Jedis jedis = getJedis(); long s = jedis.hsetnx(key, fieid, value); jedis.close(); return s; } /** * 获取hash中value的集合 * * @param key * @return List<String> */ public List<String> hvals(String key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); List<String> list = sjedis.hvals(key); sjedis.close(); return list; } /** * 在指定的存储位置加上指定的数字,存储位置的值必须可转为数字类型 * * @param key * @param fieid 存储位置 * @param value 要增加的值,可以是负数 * @return 增加指定数字后,存储位置的值 */ public long hincrby(String key, String fieid, long value) { Jedis jedis = getJedis(); long s = jedis.hincrBy(key, fieid, value); jedis.close(); return s; } /** * 返回指定hash中的所有存储名字,类似Map中的keySet方法 * * @param key * @return Set<String> 存储名称的集合 */ public Set<String> hkeys(String key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); Set<String> set = sjedis.hkeys(key); sjedis.close(); return set; } /** * 获取hash中存储的个数,类似Map中size方法 * * @param key * @return long 存储的个数 */ public long hlen(String key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); long len = sjedis.hlen(key); sjedis.close(); return len; } /** * 根据多个key,获取对应的value,返回List,如果指定的key不存在,List对应位置为null * * @param key * @param fieids 存储位置 * @return List<String> */ public List<String> hmget(String key, String... fieids) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); List<String> list = sjedis.hmget(key, fieids); sjedis.close(); return list; } public List<byte[]> hmget(byte[] key, byte[]... fieids) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); List<byte[]> list = sjedis.hmget(key, fieids); sjedis.close(); return list; } /** * 添加对应关系,如果对应关系已存在,则覆盖 * * @param key * @param map 对应关系 * @return 状态,成功返回OK */ public String hmset(String key, Map<String, String> map) { Jedis jedis = getJedis(); String s = jedis.hmset(key, map); jedis.close(); return s; } /** * 添加对应关系,如果对应关系已存在,则覆盖 * * @param key * @param map 对应关系 * @return 状态,成功返回OK */ public String hmset(byte[] key, Map<byte[], byte[]> map) { Jedis jedis = getJedis(); String s = jedis.hmset(key, map); jedis.close(); return s; } } // *******************************************Lists*******************************************// public class Lists { /** * List长度 * * @param key * @return 长度 */ public long llen(String key) { return llen(SafeEncoder.encode(key)); } /** * List长度 * * @param key * @return 长度 */ public long llen(byte[] key) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); long count = sjedis.llen(key); sjedis.close(); return count; } /** * 覆盖操作,将覆盖List中指定位置的值 * * @param key * @param index 位置 * @param value 值 * @return 状态码 */ public String lset(byte[] key, int index, byte[] value) { Jedis jedis = getJedis(); String status = jedis.lset(key, index, value); jedis.close(); return status; } /** * 覆盖操作,将覆盖List中指定位置的值 * * @param index 位置 * @param value 值 * @return 状态码 */ public String lset(String key, int index, String value) { return lset(SafeEncoder.encode(key), index, SafeEncoder.encode(value)); } /** * 在value的相对位置插入记录 * * @param where 前面插入或后面插入 * @param pivot 相对位置的内容 * @param value 插入的内容 * @return 记录总数 */ public long linsert(String key, LIST_POSITION where, String pivot, String value) { return linsert(SafeEncoder.encode(key), where, SafeEncoder.encode(pivot), SafeEncoder.encode(value)); } /** * 在指定位置插入记录 * * @param key * @param where 前面插入或后面插入 * @param pivot 相对位置的内容 * @param value 插入的内容 * @return 记录总数 */ public long linsert(byte[] key, LIST_POSITION where, byte[] pivot, byte[] value) { Jedis jedis = getJedis(); long count = jedis.linsert(key, where, pivot, value); jedis.close(); return count; } /** * 获取List中指定位置的值 * * @param key * @param index 位置 * @return 值 **/ public String lindex(String key, int index) { return SafeEncoder.encode(lindex(SafeEncoder.encode(key), index)); } /** * 获取List中指定位置的值 * * @param key * @param index 位置 * @return 值 **/ public byte[] lindex(byte[] key, int index) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); byte[] value = sjedis.lindex(key, index); sjedis.close(); return value; } /** * 将List中的第一条记录移出List * * @param key * @return 移出的记录 */ public String lpop(String key) { return SafeEncoder.encode(lpop(SafeEncoder.encode(key))); } /** * 将List中的第一条记录移出List * * @param key * @return 移出的记录 */ public byte[] lpop(byte[] key) { Jedis jedis = getJedis(); byte[] value = jedis.lpop(key); jedis.close(); return value; } /** * 将List中最后第一条记录移出List * * @param key * @return 移出的记录 */ public String rpop(String key) { Jedis jedis = getJedis(); String value = jedis.rpop(key); jedis.close(); return value; } /** * 向List尾部追加记录 * * @param key * @param value * @return 记录总数 */ public long lpush(String key, String value) { return lpush(SafeEncoder.encode(key), SafeEncoder.encode(value)); } /** * 向List头部追加记录 * * @param key * @param value * @return 记录总数 */ public long rpush(String key, String value) { Jedis jedis = getJedis(); long count = jedis.rpush(key, value); jedis.close(); return count; } /** * 向List头部追加记录 * * @param key * @param value * @return 记录总数 */ public long rpush(byte[] key, byte[] value) { Jedis jedis = getJedis(); long count = jedis.rpush(key, value); jedis.close(); return count; } /** * 向List中追加记录 * * @param key * @param value * @return 记录总数 */ public long lpush(byte[] key, byte[] value) { Jedis jedis = getJedis(); long count = jedis.lpush(key, value); jedis.close(); return count; } /** * 获取指定范围的记录,可以做为分页使用 * * @param key * @param start * @param end * @return List */ public List<String> lrange(String key, long start, long end) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); List<String> list = sjedis.lrange(key, start, end); sjedis.close(); return list; } /** * 获取指定范围的记录,可以做为分页使用 * * @param key * @param start * @param end 如果为负数,则尾部开始计算 * @return List */ public List<byte[]> lrange(byte[] key, int start, int end) { // ShardedJedis sjedis = getShardedJedis(); Jedis sjedis = getJedis(); List<byte[]> list = sjedis.lrange(key, start, end); sjedis.close(); return list; } /** * 删除List中c条记录,被删除的记录值为value * * @param key * @param c 要删除的数量,如果为负数则从List的尾部检查并删除符合的记录 * @param value 要匹配的值 * @return 删除后的List中的记录数 */ public long lrem(byte[] key, int c, byte[] value) { Jedis jedis = getJedis(); long count = jedis.lrem(key, c, value); jedis.close(); return count; } /** * 删除List中c条记录,被删除的记录值为value * * @param key * @param c 要删除的数量,如果为负数则从List的尾部检查并删除符合的记录 * @param value 要匹配的值 * @return 删除后的List中的记录数 */ public long lrem(String key, int c, String value) { return lrem(SafeEncoder.encode(key), c, SafeEncoder.encode(value)); } /** * 算是删除吧,只保留start与end之间的记录 * * @param key * @param start 记录的开始位置(0表示第一条记录) * @param end 记录的结束位置(如果为-1则表示最后一个,-2,-3以此类推) * @return 执行状态码 */ public String ltrim(byte[] key, int start, int end) { Jedis jedis = getJedis(); String str = jedis.ltrim(key, start, end); jedis.close(); return str; } /** * 算是删除吧,只保留start与end之间的记录 * * @param key * @param start 记录的开始位置(0表示第一条记录) * @param end 记录的结束位置(如果为-1则表示最后一个,-2,-3以此类推) * @return 执行状态码 */ public String ltrim(String key, int start, int end) { return ltrim(SafeEncoder.encode(key), start, end); } } }
这个工具类功能几乎很全了,举个栗子
// 定义redis的key前缀 String key = PREFIX; // 定义接收对象 List<User> user= null; // 定义jackson数据转换操作类 ObjectMapper mapper = new ObjectMapper(); // 拼接出redis的key key = key + "_" + user.getId(); // 判断key是否存在 if (!jedisKeys.exists(key)) { // 若不存在,则从数据库里面取出相应数据 user= userDao.queryUser(user); // 将相关的实体类集合转换成string,存入redis里面对应的key中 String jsonString; jsonString = mapper.writeValueAsString(user); logger.error(e.getMessage()); jedisStrings.set(key, jsonString); } else { // 若存在,则直接从redis里面取出相应数据 String jsonString = jedisStrings.get(key); // 指定要将string转换成的集合类型 JavaType javaType = mapper.getTypeFactory().constructParametricType(String.class, User.class); // 将相关key对应的value里的的string转换成对象的实体类集合 user= mapper.readValue(jsonString, javaType);
相关文章推荐
- CI框架中redis缓存相关操作文件示例代码
- Redis缓存系统-Java-Jedis操作Redis,基本操作以及 实现对象保存
- 将对象缓存到redis中
- 电商之梳理redis相关知识---java缓存技术
- CI框架中redis缓存相关操作文件示例代码
- Jeesite增加spring-data-redis缓存功能以及相关配置
- 使用走_Unix_Sockets_的_Redis_作为对象缓存
- PHP使用serialize和json_encode序列化数据并通过redis缓存文件和$GLOGALS缓存资源对象
- 使用走_Unix_Sockets_的_Redis_作为对象缓存
- redis大对象相关
- redis等缓存相关的一致性hash算法
- redis中hset相关问题,redis与缓存区别
- Redis缓存系统(1)Java-Jedis操作Redis,基本操作以及 实现对象保存
- 【ci框架】ci框架中中有关redis文件缓存相关的文件
- Redis缓存系统(一)Java-Jedis操作Redis,基本操作以及 实现对象保存
- Java在redis中进行对象的缓存
- 网站缓存技术总结( ehcache、memcache、redis对比)
- redis做session缓存,打包
- Redis 缓存数据库
- 使用spring-data-redis做缓存