spring与redis整合(二)--采用spring-data-redis方式

来源:互联网 发布:linux fork多个子进程 编辑:程序博客网 时间:2024/06/03 05:08

一、简介

在 spring与redis整合(一)中,介绍了采用原生的jedis方式,进行redis与spring的整合。

在本文,将介绍采用spring封装的redisTemple(spring-date-redis)方式,进行redis操作。

二、配置

1、jedis池配置

redis.clients.jedis.JedisPoolConfig,参数有:

a)maxTotal,池中最多可以有多少个jedis实例,默认值是8

b)maxIdle,池中最多有多少个空闲的jedis实例,默认值是8

c)minIdle,池中最小有多少个空闲的jedis实例,默认值是0

d)maxWaitMillis,获取jedis实例的最大等待毫秒数,默认值是-1

如:

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"      p:maxTotal="6000"      p:maxIdle="300"      p:minIdle="100"      p:maxWaitMillis="1500"/>
2、JedisConnectionFactory配置

org.springframework.data.redis.connection.jedis.JedisConnectionFactory,参数有:

a) hostname,redis安装地址;

b)port,端口;

c)poolConfig,jedis的池配置;

如:

<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"      p:hostName="127.0.0.1"      p:port="6379"      p:database="0"      p:poolConfig-ref="jedisPoolConfig"/>

3、序列化方式

spring data redis有4种序列化方式,

a)org.springframework.data.redis.serializer.StringRedisSerializer ,字符串方式序列化,即

<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />

b)org.springframework.data.redis.serializer.JdkSerializationRedisSerializer ,jdk默认的序列化方式,即

<bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />

c)Jackson2JsonRedisSerializer ,jackson的json序列化方式,需要指定序列化的类型。如

redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Student>(Student.class));ValueOperations<String,Student> valOps = redisTemplate.opsForValue();valOps.set("ss2",new Student(2));Student st = valOps.get("s2");

d)OxmSerializer, xml方式进行序列化,如

Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();Map<String,Object> properties = new HashMap<String, Object>();properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);   //设置缩进properties.put(Marshaller.JAXB_ENCODING,"utf-8");   //设置编码jaxb2Marshaller.setMarshallerProperties(properties);//设置Marshaller属性jaxb2Marshaller.setClassesToBeBound(Student.class);redisTemplate.setValueSerializer(new OxmSerializer(jaxb2Marshaller,jaxb2Marshaller));ValueOperations<String,Student> stuValOps = redisTemplate.opsForValue();stuValOps.set("xs2",new Student(4));Student xs2 = stuValOps.get("xs2");System.out.println(xs2);

4、RedisTemplate配置

org.springframework.data.redis.core.RedisTemplate,redisTemplate是我们操作redis的入口之一,内有参数:

a)connectionFactory,jedis的连接工厂;

b)keySerializer, key的序列化方式;

c)valueSerializer,value的序列化方式;

d)hashKeySerializer, hashKey的序列化方式;

e)hashValueSerializer,hashValue的序列化方式;

如:
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"    p:connectionFactory-ref="jedisConnectionFactory"      p:keySerializer-ref="stringRedisSerializer"      p:valueSerializer-ref="jdkSerializationRedisSerializer"      p:hashKeySerializer-ref="stringRedisSerializer"      p:hashValueSerializer-ref="jdkSerializationRedisSerializer"/>
5、StringRedisTemplate配置

org.springframework.data.redis.core.StringRedisTemplate,stringRedisTemplate是redisTemplate的子类,

同时key和value的序列化方式直接采用StringRedisSerializer方式,内有参数:

a)connectionFactory,jedis的连接工厂;

如:

<bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"p:connectionFactory-ref="jedisConnectionFactory" />
三、redis使用

1、直接使用redisTemplate的execute方法

在redisTemplate中,有很多execute重载方法,可以直接通过这些方法对数据进行操作,此时需要自己对数据进行序列化操作,如:

redisTemplate.execute(new RedisCallback() {    @Override    public Object doInRedis(RedisConnection connection) throws DataAccessException {        try {            connection.set("execKey1".getBytes("utf8"),"execVal1".getBytes("utf8"));        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        return null;    }});
2、使用RedisTemplate的封装类

在redisTemplate中,提供了redis的各种类型的封装操作类,有
a)ValueOperations<K, V> ,基本的操作类;

b)ListOperations<K, V> ,列表的操作类;

c)SetOperations<K, V>,集合的操作类;

d) HashOperations<H, HK, HV> ,哈希的操作类;

e)ZSetOperations<K, V> ,有序集合的操作类;

f)GeoOperations<K, M> ,基于地理位置信息的操作类;

如:

ValueOperations<String,String> ops = redisTemplate.opsForValue();ops.set("key1","value1");String v  = ops.get("key1");ValueOperations<String,Student> ops1 = redisTemplate.opsForValue();ops1.set("stu1",new Student(5));Student stu1 = ops1.get("stu1");
另外对上述类型,还有绑定key的操作类,也就是绑定key后,操作时就不再需要指定key,

类型与上述都是一 一对应的,有BoundValueOperations<K, V>、BoundListOperations<K, V>、

BoundGeoOperations<K, M> 、BoundSetOperations<K, V>、BoundHashOperations<H, HK, HV>、

BoundZSetOperations<K, V>。操作如:

redisTemplate.setValueSerializer(new StringRedisSerializer());BoundValueOperations<String,String> bValOps = redisTemplate.boundValueOps("bk1");bValOps.set("bv1");String bv = bValOps.get();bValOps.set("bv2");bv = bValOps.get();

此外,封装类的使用,还可以直接通过注解注入,

@Resource(name="redisTemplate")private ValueOperations<String,Student > jsonValOps;
这里类型不同,但能进行注解,原因使用了spring的editor机制,这里每个封装类都有一个对应的editor, 如ValueOperationsEditor。

3、使用StringRedisTemplate的封装类

StringRedisTemplate是RedisTemplate的子类,只把key和value的序列化方式都指定为StringRedisSerializer,

四、代码实例

1、添加maven依赖

<dependency>    <groupId>redis.clients</groupId>    <artifactId>jedis</artifactId>    <version>2.9.0</version></dependency><dependency>    <groupId>org.springframework.data</groupId>    <artifactId>spring-data-redis</artifactId>    <version>1.8.0.RELEASE</version></dependency><dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-core</artifactId>    <version>2.8.6</version></dependency><dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId>    <version>2.8.6</version></dependency><dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-annotations</artifactId>    <version>2.8.6</version></dependency><dependency>    <groupId>org.codehaus.jackson</groupId>    <artifactId>jackson-mapper-asl</artifactId>    <version>1.9.13</version></dependency><dependency>    <groupId>org.codehaus.jackson</groupId>    <artifactId>jackson-mapper-lgpl</artifactId>    <version>1.9.13</version></dependency><dependency>    <groupId>org.apache.commons</groupId>    <artifactId>commons-pool2</artifactId>    <version>2.4.2</version></dependency>
2、添加spring的redis配置
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:context="http://www.springframework.org/schema/context"       xmlns:p="http://www.springframework.org/schema/p"       xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd">    <context:component-scan base-package="com.dragon.study" />    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"          p:maxTotal="6000"          p:maxIdle="300"          p:minIdle="100"          p:maxWaitMillis="1500"    />    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"          p:hostName="127.0.0.1"          p:port="6379"          p:database="0"          p:poolConfig-ref="jedisPoolConfig"    />    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"        p:connectionFactory-ref="jedisConnectionFactory"          p:keySerializer-ref="stringRedisSerializer"          p:valueSerializer-ref="jdkSerializationRedisSerializer"          p:hashKeySerializer-ref="stringRedisSerializer"          p:hashValueSerializer-ref="jdkSerializationRedisSerializer"    />    <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"    p:connectionFactory-ref="jedisConnectionFactory" />    <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />    <bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /></beans>
3、注解方式使用redis

@Service("studentRedisSerive")public class StudentRedisSeriveImpl{    @Resource    private RedisTemplate<String,Student > redisTemplate;    @Resource    private StringRedisTemplate stringRedisTemplate;    @Resource(name="redisTemplate")    private ValueOperations<String,Student > valOps;    public void saveStu(String key ,Student stu){        valOps.set(key,stu);    }    public Student getStu(String key){        return valOps.get(key);    }}
4、测试使用

public class SpringRedisMain {    public static void main(String[] args) {        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring-redis.xml");        RedisTemplate redisTemplate = (RedisTemplate) ac.getBean("redisTemplate");  //获取redisTemple        StringRedisTemplate stringRedisTemplate = (StringRedisTemplate) ac.getBean("stringRedisTemplate");  //获取stringRedisTemplate        ////////////////////////通过服务中的注解使用redis/////////////////////////        StudentRedisSeriveImpl studentRedisSerive = (StudentRedisSeriveImpl) ac.getBean("studentRedisSerive");          studentRedisSerive.saveStu("stu7",new Student(7));          Student st = studentRedisSerive.getStu("stu7");        System.out.println(st);        ////////////////////////使用的原生redisTemplate的execute方法//////////////////////////////        redisTemplate.execute(new RedisCallback() {              @Override            public Object doInRedis(RedisConnection connection) throws DataAccessException {                try {                    connection.set("execKey1".getBytes("utf8"),"execVal1".getBytes("utf8"));                } catch (Exception e) {                    e.printStackTrace();                }                return null;            }        });                ////////////////////////通过spring对redis的封装类操作redis////////////////////////////////        ValueOperations<String,String> ops = redisTemplate.opsForValue();        ops.set("key1","value1");        String v  = ops.get("key1");        ValueOperations<String,Student> ops1 = redisTemplate.opsForValue();        ops1.set("stu1",new Student(5));        Student stu1 = ops1.get("stu1");                //////////////////////通过spring对redis的封装类操作redis(绑定了key)//////////////////////////////////        redisTemplate.setValueSerializer(new StringRedisSerializer());        BoundValueOperations<String,String> bValOps = redisTemplate.boundValueOps("bk1");        bValOps.set("bv1");        String bv = bValOps.get();        bValOps.set("bv2");        bv = bValOps.get();        System.out.println(bv);        ///////////////////////////设置value的序列化方式为json///////////////////////////////////////////////        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Student>(Student.class));        ValueOperations<String,Student> valOps = redisTemplate.opsForValue();        valOps.set("stu5",new Student(5));        Student st1 = valOps.get("stu5");        ////////////////////////////设置value的序列化方式为xml/////////////////////////////        Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();  //设置xml序列化配置        Map<String,Object> properties = new HashMap<String, Object>();        properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);   //设置缩进        properties.put(Marshaller.JAXB_ENCODING,"utf-8");   //设置编码        jaxb2Marshaller.setMarshallerProperties(properties);//设置Marshaller属性        jaxb2Marshaller.setClassesToBeBound(Student.class);        redisTemplate.setValueSerializer(new OxmSerializer(jaxb2Marshaller,jaxb2Marshaller));  //设置xml序列化        ValueOperations<String,Student> stuValOps = redisTemplate.opsForValue();        stuValOps.set("xs2",new Student(4));        Student xs2 = stuValOps.get("xs2");        System.out.println(xs2);    }}



原创粉丝点击