1.简单介绍
redis 是基于C语言开发。
redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。
redis 是一个 缓存数据库(片面的理解) 既可以做缓存,也可以将数据持久化到磁盘中!
2.pom.xml 引入相关jar (曾经因jar 版本问题出现报错,请注意)
org.apache.commons commons-pool2 2.2 org.springframework.data spring-data-redis 1.7.5.RELEASE redis.clients jedis 2.9.0
3.spring-redis.xml 配置文件,配置关键bean redisTemplate
上文中使用到的配置文件 redis-config.properteis
redis.maxIdle=1redis.maxTotal=5redis.maxWaitMillis=30000redis.testOnBorrow=trueredis.hostname=127.0.0.1redis.port=6379
4.redis 有4个关键的接口如下
private ValueOperations<K, V> valueOps;
private ListOperations<K, V> listOps;
private SetOperations<K, V> setOps;
private ZSetOperations<K, V> zSetOps;
分别对应redis的数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)
具体使用如下,上代码:
//添加字符串ValueOperationsvalue = this.redisTemplate.opsForValue();value.set("hello", "讨厌");System.out.println(value.get("hello"));//添加 一个 hash集合HashOperations hash =redisTemplate.opsForHash();hash.put("沃尔玛","水果", "苹果");hash.put("沃尔玛","饮料", "红牛");System.out.println(hash.entries("沃尔玛"));//添加一个list 集合ListOperations list = redisTemplate.opsForList();list.rightPush("课程", "chinese");list.rightPush("课程", "englise");System.out.println(list.range("lpList", 0, 1));//添加 一个 set 集合SetOperations set = redisTemplate.opsForSet();set.add("lpSet", "lp");set.add("lpSet", "26");set.add("lpSet", "178cm");//输出 set 集合System.out.println(set.members("lpSet"));//添加有序的 set 集合ZSetOperations zset = redisTemplate.opsForZSet();zset.add("lpZset", "lp", 0);zset.add("lpZset", "26", 2);zset.add("lpZset", "178cm", 1);//输出有序 set 集合System.out.println(zset.rangeByScore("lpZset", 0, 2));