Redis是key-value存储的非关系型数据库。Spring Data Redis包含了多个模板实现,用来完成Redis数据库的数据存取功能

1、如何连接Redis?

Spring Data Redis提供了JedisConnectFactory连接工厂(不止这一个)

<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="192.168.1.106"></property>
</bean>

2、使用模板

  Spring Data Redis提供了RedisTemplate 和 StringRedisTemplate模板。模板封装了对redis操作,提供了较高级的数据访问方案。从名字可以看出后者只关注字符串类型,当redis的key和value都是字符串时候建议使用StringRedisTemplate

RedisTemplate的很多功能以子API的形式提供,他们区分了单个值和集合值得场景。

package com.cn.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component; import java.util.List;
import java.util.Set; @Component
public class JedisUtil { @Autowired
private RedisTemplate<String, Object> redisTemplate; //字符串
public void setStr(String key, Object value){
redisTemplate.opsForValue().set(key, value);
}
public Object getStr(String key){
return redisTemplate.opsForValue().get(key);
}
//list集合
public void lpush(String key, Object value){
redisTemplate.opsForList().leftPush(key, value);
}
public Object lpop(String key){
return redisTemplate.opsForList().leftPop(key);
}
public List<Object> lrange(String key, long start , long end){
return redisTemplate.opsForList().range(key, start, end);
}
//set集合
public void addSet(String key, String value){
redisTemplate.opsForSet().add(key, value);
}
public Set<Object> getSet(String key){
return redisTemplate.opsForSet().members(key);
}
//hash集合
public void hset(String key, String key1, String value){
redisTemplate.opsForHash().put(key, key1, value);
}
public Object hget(String key, String key1){
return redisTemplate.opsForHash().get(key, key1);
}
public Set<Object> getKeys(String key){
return redisTemplate.opsForHash().keys(key);
} }

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:springMvc.xml", "classpath:spring-source.xml"})
public class JedisUtilTest { @Autowired
private JedisUtil jedisUtil; @Test
public void setStr() throws Exception {
jedisUtil.setStr("shoudu","beijing");
} @Test
public void getStr() throws Exception {
Object obj=jedisUtil.getStr("shoudu");
System.out.println(obj);
} @Test
public void lpush() throws Exception {
jedisUtil.lpush("testlist",new User("ii","ll")); } @Test
public void lpop() throws Exception {
Object obj= jedisUtil.lpop("testlist");
System.out.println(obj);
} @Test
public void lrange() throws Exception {
List<Object> list=jedisUtil.lrange("testlist", 0 , -1);
System.out.println(list);
} @Test
public void addSet() throws Exception {
jedisUtil.addSet("testset", "jj2");
} @Test
public void getSet() throws Exception {
Object obj = jedisUtil.getSet("testset");
System.out.println(obj);
} @Test
public void hset() throws Exception {
jedisUtil.hset("testhash", "name", "liming");
} @Test
public void hget() throws Exception {
Object obj=jedisUtil.hget("testhash","name");
System.out.println(obj);
} @Test
public void getKeys() throws Exception {
Set<Object> keys=jedisUtil.getKeys("testhash");
System.out.println(keys);
} @Test
public void muchOps() throws Exception{
BoundHashOperations<String, String, Object> boundHashOperations=
jedisUtil.redisTemplate.boundHashOps("testhash");
String str=boundHashOperations.getKey();
System.out.println(str);
Object obj=boundHashOperations.get("name");
System.out.println(obj);
boundValueOperations.put("age",123);
boundValueOperations.put("school","beida");
Set<String> keys=boundHashOperations.keys();
System.out.println(keys);
}
}

  以上测试方法,仅仅测试了每种redis数据类型的部分方法。注意,最后muchOps()测试方法,redisTemplate提供绑定key(此处为hash类型的key,其它类型类似)的方式执行操作,整个方法中仅仅一个地方使用了key,即jedisUtil.redisTemplate.boundHashOps("testhash"),对返回的boundValueOperations执行的所有操作都会应用到这个key上。

3、使用key和value的序列化器

  当某个key-value条目保存到Redis存储时候,key和value都会使用Redis序列化器进行序列化。Spring Date Redis 提供了多个序列化器:

1)JdkSerializationRedisSerializer:POJO对象的存取场景,使用JDK本身序列化机制,将pojo类通过ObjectInputStream/ObjectOutputStream进行序列化操作,最终redis-server中将存储字节序列。是目前最常用的序列化策略。
2)StringRedisSerializer:Key或者value为字符串的场景,根据指定的charset对数据的字节序列编码成string,是“new String(bytes, charset)”和“string.getBytes(charset)”的直接封装。是最轻量级和高效的策略。
3)JacksonJsonRedisSerializer:jackson-json工具提供了javabean与json之间的转换能力,可以将pojo实例序列化成json格式存储在redis中,也可以将json格式的数据转换成pojo实例。因为jackson工具在序列化和反序列化时,需要明确指定Class类型,因此此策略封装起来稍微复杂。【需要jackson-mapper-asl工具支持】
4)OxmSerializer:提供了将javabean与xml之间的转换能力,目前可用的三方支持包括jaxb,apache-xmlbeans;redis存储的数据将是xml工具。不过使用此策略,编程将会有些难度,而且效率最低;不建议使用。【需要spring-oxm模块的支持

  • RedisTemplate中需要声明4种serializer,默认为“JdkSerializationRedisSerializer”:

a) keySerializer :对于普通K-V操作时,key采取的序列化策略
    b) valueSerializer:value采取的序列化策略
    c) hashKeySerializer: 在hash数据结构中,hash-key的序列化策略
    d) hashValueSerializer:hash-value的序列化策略

  • StringRedisTemplate也需要申明4中serializer,但是默认为“StringRedisSerializer”,可以看StringRedisTemplate类的源码:
package org.springframework.data.redis.core;

import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; public class StringRedisTemplate extends RedisTemplate<String, String> {
public StringRedisTemplate() {
RedisSerializer<String> stringSerializer = new StringRedisSerializer(); //StringRedisSerializer序列器
this.setKeySerializer(stringSerializer);
this.setValueSerializer(stringSerializer);
this.setHashKeySerializer(stringSerializer);
this.setHashValueSerializer(stringSerializer);
} public StringRedisTemplate(RedisConnectionFactory connectionFactory) {
this();
this.setConnectionFactory(connectionFactory);
this.afterPropertiesSet();
} protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
return new DefaultStringRedisConnection(connection);
}
}

spring-集成redis的更多相关文章

  1. Spring集成Redis集群(含spring集成redis代码)

    代码地址如下:http://www.demodashi.com/demo/11458.html 一.准备工作 安装 Redis 集群 安装参考: http://blog.csdn.net/zk6738 ...

  2. spring 集成 redis -- pub/sub

    redis除了常用的当做缓存外,还可以当做简单的消息中间件,实现消息发布订阅 spring集成redis,可以使用spring-data-redis 首先引入相关maven依赖(此处我spring相关 ...

  3. spring集成redis

    redis是一种非关系型数据库,与mongoDB不同的是redis是内存数据库,所以访问速度很快.常用作缓存和发布-订阅式的消息队列.redis官方没有提供windows版本的软件.windows版本 ...

  4. spring 集成redis客户端jedis(java)

    spring集成jedis简单实例   jedis是redis的java客户端,spring将redis连接池作为一个bean配置. “redis.clients.jedis.JedisPool”,这 ...

  5. spring集成redis,集成redis集群

    原文:http://chentian114.iteye.com/blog/2292323 1.通过spring-data-redis集成redis pom.xml依赖包 <project xml ...

  6. Spring集成Redis方案(spring-data-redis)(基于Jedis的单机模式)(待实践)

    说明:请注意Spring Data Redis的版本以及Spring的版本!最新版本的Spring Data Redis已经去除Jedis的依赖包,需要自行引入,这个是个坑点.并且会与一些低版本的Sp ...

  7. spring集成redis——主从配置以及哨兵监控

    Redis主从模式配置: Redis的主从模式配置是非常简单的,首先我们需要有2个可运行的redis环境: master node : 192.168.56.101 8887 slave node: ...

  8. Spring集成Redis缓存

    作者:13 GItHub:https://github.com/ZHENFENG13 版权声明:本文为原创文章,未经允许不得转载. 整合Redis 本来以为类似的Redis教程和整合代码应该会很多,因 ...

  9. Spring+SpringMVC+MyBatis+easyUI整合进阶篇(十二)Spring集成Redis缓存

    作者:13 GitHub:https://github.com/ZHENFENG13 版权声明:本文为原创文章,未经允许不得转载. 整合Redis 本来以为类似的Redis教程和整合代码应该会很多,因 ...

  10. Spring集成Redis使用注解

    转载:http://blog.csdn.net/u013725455/article/details/52129283 使用Maven项目,添加jar文件依赖: <project xmlns=& ...

随机推荐

  1. 【NLP_Stanford课堂】语言模型4

    平滑方法: 1. Add-1 smoothing 2. Add-k smoothing 设m=1/V,则有 从而每一项可以跟词汇表的大小相关 3. Unigram prior smoothing 将上 ...

  2. 【Leetcode】【Medium】Search Insert Position

    Given a sorted array and a target value, return the index if the target is found. If not, return the ...

  3. cnpm install 之后 Angular2 Build --prod 报错

    95% emittingUnhandled rejection Error: ENOENT: no such file or directory, open 'E:\git_0.28\adminTem ...

  4. HDU ACM 2895-Edit distance

    Edit distance Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other) Total ...

  5. yii2.0里的redirect跳转方法

    在yii2框架里难免会出现跨控制器跳转,调用方法等,这就用到了redirect了, 带参数的 $control=Yii::app()->runController('site/show/id/2 ...

  6. Code First TPH、TPT、TPC与继承类

    一.Table Per Hierarchy (TPH,默认) 每个层次结构共用一个表,类的每一个属性都必须是可空的. 1.默认行为 只建立一个表,把基类和子类中的所有属性都映射为表中的列. 在这种处理 ...

  7. 41. First Missing Positive (sort) O(n) time

    Given an unsorted integer array, find the smallest missing positive integer. Example 1: Input: [1,2, ...

  8. 九.mysql数据库多实例安装mysqld_multi [start,stop,report]

    经常应为系统硬件短缺,导致需要在同一台硬件服务器上面安装多个mysql实例.之前的文章四·安装mysql-5.7.16-linux-glibc2.5-x86_64.tar.gz(基于Centos7源码 ...

  9. 3.为JDeveloper添加不能的workspace

    1.点击选中JDeveloper,在属性中,选中快捷方式, 可以看到目标中的值为C:\Oracle\Middleware\jdeveloper\jdeveloper.exe, 只需要在修改为C:\Or ...

  10. [转]C# 指针之美

     将C#图像库的基础部分开源了(https://github.com/xiaotie/GebImage).这个库比较简单,且离成熟还有一段距离,但它是一种新的开发模式的探索:以指针和非托管内存为主的C ...