Redis基础学习(二)—数据类型
一、Redis支持的数据类型
Redis中存储数据是通过key-value存储的,对于value的类型有以下几种:
(1)字符串。
(2)Map
(3)List
(4)Set
public class RedisPoolManager{
// Redis服务器IP
private static String HOST = "192.168.109.157";
// Redis的端口号
private static int PORT = 6379;
// 可用连接实例的最大数目,默认值为8;
// 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static int MAX_ACTIVE = 1024;
// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = 200;
// 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
private static int MAX_WAIT = 10000;
private static int TIMEOUT = 10000;
// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = true;
private static JedisPool jedisPool = null;
/*
* 初始化Redis连接池
*/
static{
try{
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setMaxTotal(MAX_ACTIVE);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config,HOST,PORT,TIMEOUT);
}catch(Exception e){
e.printStackTrace();
}
}
/*
* 获取Jedis实例
*/
public synchronized static Jedis getJedis(){
try{
if(jedisPool != null){
Jedis resource = jedisPool.getResource();
return resource;
}else{
return null;
}
}catch(Exception e){
e.printStackTrace();
return null;
}
}
/*
* 释放jedis资源
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResourceObject(jedis);
}
}
}
1.String类型
set: 设置key值。
get: 获取key值。
del: 删除key。append: 追加key值。
incr: key值自增1。
incrBy: key值自增,指定步长。
decr: key值自减1。
decrBy: key值自减,指定步长。
expire: 为key设置过期时间(秒数)。
setex: 设置key值,可指定存活时间(秒数)。setnx: 设置key值。key不存在才会设置,如果key存在则回滚操作,结果返回0,表示没有设置成功。
ttl: time to live,获取key的存活时间(秒),-1表示永不过期。
persist: 去掉key的expire设置,不再有失效时间。
/*
* set:设置key值
* get:获取key值
* del:删除key
* append:追加key值
* incr:key值自增1
* incrBy:key值自增,指定步长
* decr:key值自减1
* decrBy:key值自减,指定步长
* expire:为key设置过期时间(秒数)
* setex:设置key值,可指定存活时间(秒数)
* setnx:设置key值。key不存在才会设置,如果key存在则回滚操作,结果返回0,表示没有设置成功
* ttl:time to live,获取key的存活时间(秒),-1表示永不过期
* persist:去掉key的expire设置,不再有失效时间
*/
@Test
public void testString(){
Jedis jedis = RedisPoolManager.getJedis(); //设置key值
jedis.set("Tom","22");
//获取key值
String result = jedis.get("Tom");
System.out.println("Tom : " + result); //删除key
jedis.del("Tom");
result = jedis.get("Tom");
System.out.println("Tom : " + result); jedis.set("num","1");
//key值自增,并指定步长
jedis.incrBy("num",5);
jedis.incrBy("num",5);
System.out.println("nun : " + jedis.get("num"));
//key值自减,并指定步长
jedis.decrBy("num",5);
System.out.println("nun : " + jedis.get("num")); //设置key值,可指定存活时间(秒数)
jedis.setex("AAA",5,"22");
System.out.println("5秒前---AAA : " + jedis.get("AAA"));
try{
TimeUnit.SECONDS.sleep(5);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("5秒后---AAA : " + jedis.get("AAA"));
}
结果:

2.Map类型
hmset: 设置key值,值类型为map对象。
type: 返回key值的类型,可能值有none, string, hash, set, list, zset。
hkeys: 获取所有key。
hvals: 获取所有key对应的值。hmget: 一次性获取多个field的值。
hexists: 判断field是否存在。
hset: 设置field的值。
hgetAll: 获取全部内容。
hget: 获取field的值。
hdel: 删除field。
hincrBy: field值自增1。
hlen: 计算field的数目。
hsetnx: 设置key值。field不存在才会设置,如果field存在则回滚操作,结果返回0,表示没有设置成功。可以用来实现分布式锁。
/*
* hmset:设置key值,值类型为map对象
* type:返回key值的类型,可能值有none, string, hash, set, list, zset
* hkeys:获取所有key
* hvals:获取所有key对应的值
* hmget:一次性获取多个field的值
* hexists:判断field是否存在
* hset:设置field的值
* hgetAll:获取全部内容
* hget:获取field的值
* hdel:删除field
* hincrBy:field值自增1
* hlen:计算field的数目
* hsetnx:设置key值。field不存在才会设置,如果field存在则回滚操作,结果返回0,表示没有设置成功。可以用来实现分布式锁
*/
@Test
public void testMap(){ Jedis jedis = RedisPoolManager.getJedis(); Map<String,String> map = new HashMap<String,String>();
map.put("username","AAA");
map.put("address","北京市昌平区");
map.put("age","22"); //设置key值,值类型为map对象
jedis.hmset("user",map); //返回key值的类型,可能值有none, string, hash, set, list, zset
System.out.println("type: " + jedis.type("user"));
//获取所有key
System.out.println("hkeys: " + jedis.hkeys("user"));
//获取所有key对应的值
System.out.println("hvals: " + jedis.hvals("user"));
//一次性获取多个field的值
System.out.println("hmget: " + jedis.hmget("user","username","address"));
//判断field是否存在
System.out.println("hexists: " + jedis.hexists("user","username")); //设置field的值
jedis.hset("user","username","AAA001");
//获取field的值
System.out.println("hget: " + jedis.hget("user","username"));
System.out.println("hgetAll: " + jedis.hgetAll("user"));
}
结果:

3.Set类型
sadd: 往set对象中添加一个值。
smembers: 取得set中所有的值。
sismember: 判断一个值是否在set中存在。
srandmember: 从set中随机取得一个值。
srem: 从set中删除一个值。
scard: 返回set的item个数。
/*
* sadd:往set对象中添加一个值
* smembers:取得set中所有的值
* sismember:判断一个值是否在set中存在
* srandmember:从set中随机取得一个值
* srem:从set中删除一个值
* scard:返回set的item个数
*/
@Test
public void testSet(){ Jedis jedis = RedisPoolManager.getJedis(); //往set对象中添加一个值
jedis.sadd("uid","u001");
jedis.sadd("uid","u002");
jedis.sadd("uid","u003"); System.out.println("type : " + jedis.type("uid")); //取得set中所有的值
System.out.println(jedis.smembers("uid")); //判断一个值是否在set中存在
System.out.println(jedis.sismember("uid","u003"));
//从set中随机取得一个值
System.out.println(jedis.srandmember("uid"));
//从set中删除一个值
jedis.srem("uid","u003");
System.out.println(jedis.smembers("uid"));
//返回set的item个数
System.out.println(jedis.scard("uid")); }
结果:

4.List类型
rpush: 从列表尾部插入多个元素。
llen: 返回列表中的元素的数量。
lpop: 从列表头部移除并返回list的第一个元素。
lrem: 从头部开始找,删除n个值。
lrange: 从列表中获取指定范围的子集。
/*
* rpush:从列表尾部插入多个元素
* llen:返回列表中的元素的数量
* lpop:从列表头部移除并返回list的第一个元素
* lrem:从头部开始找,删除n个值
* lrange:从列表中获取指定范围的子集
*/
@Test
public void testList(){ Jedis jedis = RedisPoolManager.getJedis(); //从列表尾部插入多个元素
jedis.rpush("list","AAA","BBB","CCC","DDD");
//返回列表中的元素的数量
System.out.println("llen: " + jedis.llen("list"));
//从列表头部移除并返回list的第一个元素
String item = jedis.lpop("list");
System.out.println("lpop: " + item);
System.out.println("llen: " + jedis.llen("list"));
jedis.rpush("list","111","222","333","444","AAA");
//从头部开始找,删除n个值
jedis.lrem("list",1,"AAA");
System.out.println("llen: " + jedis.llen("list"));
}
结果:

5.工具类
public class RedisUtil {
private static String HOST = "192.168.109.157";
private static int PORT = 6379;
private static JedisPool pool = null;
static {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(128);
config.setMaxIdle(80);
config.setMaxWaitMillis(2001);
pool = new JedisPool(config, HOST, PORT, 2000);
}
/**
* 把key存入redis中
*
* @param key k
* @param value v
* @param seconds 过期时间(秒)
* @return boolean
*/
public static boolean set(byte[] key, byte[] value, int seconds) {
Jedis jedis = null;
try {
jedis = pool.getResource();
String result = jedis.set(key, value);
if (seconds > 0) {
Long r = jedis.expire(key, seconds);
}
} catch (Exception e) {
return false;
} finally {
if (null != jedis) {
jedis.close();
}
}
return true;
}
public static byte[] get(byte[] key) {
byte[] value = null;
Jedis jedis = null;
try {
jedis = pool.getResource();
value = jedis.get(key);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return value;
}
/**
* 向缓存中设置对象
*
* @param key key
* @param obj value
* @return boolean
*/
public static boolean set(String key, Object obj, Integer seconds) {
Jedis jedis = null;
try {
jedis = pool.getResource();
ObjectMapper mapper = new ObjectMapper();
String value = mapper.writeValueAsString(obj);
jedis.set(SafeEncoder.encode(key), SafeEncoder.encode(value));
if (seconds != null) {
jedis.expire(key, seconds);
}
return true;
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return false;
}
/**
* 向缓存中设置对象
*
* @param key key
* @param value value
* @return boolean
*/
public static boolean set(String key, String value, Integer seconds) {
Jedis jedis = null;
try {
jedis = pool.getResource();
jedis.set(SafeEncoder.encode(key), SafeEncoder.encode(value));
if (seconds != null) {
jedis.expire(key, seconds);
}
return true;
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return false;
}
/**
* 移除缓存中设置对象
*
* @param keys 被删除的KEYS
* @return Long 被删除个数
*/
public static Long del(String... keys) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.del(keys);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
/**
* 根据key 获取对象
*
* @param key key
* @return T
*/
public static <T> T get(String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = pool.getResource();
String v = jedis.get(key);
if (StringUtils.isNotEmpty(v)) {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(v, clazz);
}
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
/**
* 根据key值得到String类型的返回值
*
* @param key key
* @return String
*/
public static String get(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
String v = jedis.get(key);
if (StringUtils.isNotEmpty(v)) {
return v;
}
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
public static Boolean exists(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.exists(key);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
/**
* redis的list操作:
* 把元素插入到列表的尾部
*
* @param key KEY
* @param strings 要插入的值,变参
* @return 返回插入后list的大小
*/
public static Long rpush(String key, String... strings) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.rpush(key, strings);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
/**
* redis的list操作:
* 根据开始与结束下标取list中的值
*
* @param key KEY
* @param start 开始下标
* @param end 结束下标
* @return List<String>
*/
public static List<String> lrange(String key, int start, int end) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.lrange(key, start, end);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
/**
* redis的list操作:
* 取列表的长度
*
* @param key key
* @return Long
*/
public static Long llen(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.llen(key);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
/**
* redis的list操作:
* 根据值移除list中的元素
*
* @param key KEY
* @param count :
* count > 0 : 从表头开始向表尾搜索,移除与 value 相等的元素,数量为 count 。
* count < 0 : 从表尾开始向表头搜索,移除与 value 相等的元素,数量为 count 的绝对值。
* count = 0 : 移除表中所有与 value 相等的值。
* @param value 要删除的值
* @return 返回被移除的个数
*/
public static Long lrem(String key, long count, String value) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.lrem(key, count, value);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
public static boolean setLong(String key, Long value) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return "OK".equals(jedis.set(key, String.valueOf(value)));
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return false;
}
public static Long getLong(String key) {
String result = get(key);
return result == null ? null : Long.valueOf(result);
}
public static Long incrBy(String key, Long increment) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.incrBy(key, increment);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
public static Long hashSet(String key, String field, String value) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.hset(key, field, value);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return -1L;
}
public static Long hashSetLong(String key, String field, Long value) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.hset(key, field, String.valueOf(value));
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return -1L;
}
public static Long hashIncrBy(String key, String field, Long increment) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.hincrBy(key, field, increment);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return -1L;
}
public static Map<String, String> hashGetAll(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.hgetAll(key);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
public static Set<String> hashKeys(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.hkeys(key);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
public static Long hashDelAll(String key, String... fields) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.hdel(key, fields);
} catch (Exception e) {
} finally {
if (null != jedis) {
jedis.close();
}
}
return null;
}
}
测试:
@Test
public void testObj(){ User user = new User("001","张三","朝阳区"); RedisUtil.set("user",user,3600000); User user2 = RedisUtil.get("user",User.class);
System.out.println(user2); }
结果:
User [id=001, username=张三, address=朝阳区]
Redis基础学习(二)—数据类型的更多相关文章
- Python入门基础学习 二
Python入门基础学习 二 猜数字小游戏进阶版 修改建议: 猜错的时候程序可以给出提示,告诉用户猜测的数字偏大还是偏小: 没运行一次程序只能猜测一次,应该提供多次机会给用户猜测: 每次运行程序,答案 ...
- Python基础学习二
Python基础学习二 1.编码 utf-8编码:自动将英文保存为1个字符,中文3个字符.ASCll编码被囊括在内. unicode:将所有字符保存为2给字符,容纳了世界上所有的编码. 2.字符串内置 ...
- redis命令学习(二) · THIS SPACE
列表(Lists)操作命令 Redis列表是简单的字符串列表,按照插入顺序排序. 你可以添加一个元素导列表的头部(左边)或者尾部(右边)LPUSH命令插入一个新的元素导头部,而RPUSH插入一个新元素 ...
- Go基础学习(二)
数组[array] 数组定义[定义后长度不可变] 12 symbol := [...]string{USD: "$", EUR: "€", GBP: " ...
- Redis 学习(二) —— 数据类型及操作
Redis支持string.list.set.zset.hash等数据类型,这一篇学习redis的数据类型.命令及某些使用场景. 一.String,字符串 字符串是 Redis 最基本的数据类型.一个 ...
- redis基础学习总结
学习目标: 1.redis特点及安装 2.redis键值操作 3.redis数据类型[string, link,set,orderset,hash] 4.事务 5.消息 ...
- Django基础学习二
今天继续学习django的基础 学习用户提交url如何获得返回值 1.首先需要在工程的urls文件定义指定的urls要路由给哪个函数 在这个例子中,我们定义home的urls路由给views里的tes ...
- Redis基础(二)数据库
数据库 Redis服务器的所有数据库都保存在redisServer.db数组中,而数据库的数量则由redisServer.dbnum属性保存. struct redisServer { // .. / ...
- redis 基础学习总结
背景:因为项目用到了redis,加上之前一直听说了redis,但一直没有用过,正好项目现在要用到了,抽时间简单学习了下,做个记录总结下. 一 .Redis简介 介绍Redis之前,先了解下NoSQL ...
随机推荐
- kafka c++客户端编译
Kafka是一种高吞吐量的分布式发布订阅消息系统,它可以处理消费者规模的网站中的所有动作流数据. 这种动作(网页浏览,搜索和其他用户的行动)是在现代网络上的许多社会功能的一个关键因素. 这些数据通常是 ...
- 微信群之Java技术红包问答
缘起 年前公司拿到B+轮融资,相应的在战略上也做了很大的调整,毕竟B轮要做的事情不仅仅是增加用户数,于是乎公司在2017年的开头补充了一部分技术团队,这次人员选择上主要针对一些工作经验在1-2年的技术 ...
- 2017-3-2 C#基础 集合
要使用集合必须先引用命名空间,using System.Collections; 集合与数组的不同: 数组:同一类型,固定长度集合:不同类型,不固定长度 集合主要分为六大类:普通集合,泛型集合,哈希表 ...
- ERP库位分布看板(库位管理)
客户正在使用的看板管理,根据厂家需求,做的二次开发. 一:看板效果 二:客户需求 1.客户需求:XX是一家汽车零部件(胶管,硅胶管等)的生产厂家,因此对原料,半成品的有效期有严格的要求. 多次调研得知 ...
- Java系统属性与Preferences API的简单介绍
系统属性在和Preferences API都是键值对,前者只能当前应用程序中共享数据,而后者可以在用户的各个应用或用户之间共享数据. 系统属性 Java 的系统属性决定了 Java 程序实际运行的环境 ...
- Git基础教程(二)
继续上篇Git基础教程(一),在开篇之前,先回顾一下上篇中的基本命令. 配置命令:git config --global * 版本库初始化:git init 向版本库添加文件:git add * 提交 ...
- Asp.Net Core Authentication Middleware And Generate Token
.mytitle { background: #2B6695; color: white; font-family: "微软雅黑", "宋体", "黑 ...
- wemall app商城源码Android数据的SharedPreferences储存方式
wemall-mobile是基于WeMall的Android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.本文分享wemall app商城源码Android数据 ...
- javascript继承---组合式继承
原型链继承和构造函数继承中存在着很多的缺陷,所以,使用组合式继承了进行弥补这些缺陷 //组合继承 //父函数 function a(){ this.name = "兔子只吃胡萝卜" ...
- JAVA连接数据库后,对数据库进行增删改查
1.Statement 增删改: 方法:execute(String SQL) String url="jdbc:Access:///E://A//shop.mdb"; Conne ...