Spring中使用Redis

Spring中使用Redis

在Spring中使用Redis,除了使用jedis.jar,还要使用spring-data-redis.jar

要注意的是jar包和Spring版本的兼容性问题,这里使用的jar包版本如下,使用的Maven创建项目,pom.xml文件内容如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.wz</groupId>
    <artifactId>redis</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>redis Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <!-- spring版本号 -->
        <spring.version>4.3.2.RELEASE</spring.version>
        <!-- mybatis版本号 -->
        <mybatis.version>3.4.2</mybatis.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.7.2.RELEASE</version>
        </dependency>



    </dependencies>
    <build>
        <finalName>redis</finalName>
    </build>
</project>

项目的结构如下:

项目结构

这里使用的是Spring提供的RedisTemplate操作Redis,先看applicationContext.xml文件的内容,以后再做解释,如下:

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!--最大空闲数 -->
        <property name="maxIdle" value="50" />
        <!--最大连接数 -->
        <property name="maxTotal" value="100" />
        <!--最大等待时间 -->
        <property name="maxWaitMillis" value="20000" />
    </bean>

    <bean id="connectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="localhost" />
        <property name="port" value="6379" />
        <!--<property name="password" value="paasword"/> -->
        <property name="poolConfig" ref="poolConfig" />
    </bean>

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

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

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="keySerializer" ref="stringRedisSerializer" />
        <property name="valueSerializer" ref="jdkSerializationRedisSerializer" />
    </bean>

</beans>

在大部分情况下要使用到连接池,所以先要配置一个JedisPoolConfig对象

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!--最大空闲数 -->
        <property name="maxIdle" value="50" />
        <!--最大连接数 -->
        <property name="maxTotal" value="100" />
        <!--最大等待时间 -->
        <property name="maxWaitMillis" value="20000" />
    </bean>

在使用Spring提供的RedisTemplate之前需要配置Spring提供的连接工厂

    <bean id="connectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="localhost" />
        <property name="port" value="6379" />
        <!--<property name="password" value="paasword"/> -->
        <property name="poolConfig" ref="poolConfig" />
    </bean>
  • hostName - 表示服务器,默认是localhost,如果是本机可以不配置它
  • port - 表示端口,默认是6379,如果使用默认的Redis端口,也可以不配置它
  • password - 表示密码,在需要密码连接Redis的场合需要配置它
  • poolConfig - 连接池配置对象

配置RedisTemplate

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

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

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="keySerializer" ref="stringRedisSerializer" />
        <property name="valueSerializer" ref="jdkSerializationRedisSerializer" />
    </bean>

JdkSerializationRedisSerializerStringRedisSerializer的解释?

普通的连接使用没有办法把Java对象直接存入Redis,所以需要字节提供方案,通常的做法是将对象序列化,然后使用Redis进行存储,而取回序列化的内容后,再通过转换变为Java对象。Spring模板中提供了封装的方案,在它内部提供了RedisSerializer接口(org.springframework.data.redis.serializer.RedisSerializer)和一些实现类

可以选择Spring提供的方案去处理序列化,也可以去实现在spring data redis中定义的RedisSerializer接口,在Spring中提供了以下几种实现RedisSerializer接口的序列化器

序列化器

  • StringRedisSerializer使用字符串进行序列化
  • JdkSerializationRedisSerializer使用JDK的序列化器进行转化

使用它们就能够帮助我们把对象通过序列化存储到Redis中,也可以把Redis存储的内容转换为Java对象
Spring提供的RedisTemplate有两个属性

  • keySerializer - 键序列器
  • valueSerializer - 值序列器

如上就配置了一个RedisTemplate对象,并且spring data redis知道会用对应的序列化器去转换Redis的键值

如下的例子,创建一个Role对象,使用Redis来保存对象,如下:

Role类:

package com.redis.model;

import java.io.Serializable;

public class Role implements Serializable{

    private static final long serialVersionUID = -5441450700658826765L;

    private long id;
    private String rolename;
    private String note;

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getRolename() {
        return rolename;
    }
    public void setRolename(String rolename) {
        this.rolename = rolename;
    }
    public String getNote() {
        return note;
    }
    public void setNote(String note) {
        this.note = note;
    }
    @Override
    public String toString() {
        return "Role [id=" + id + ", rolename=" + rolename + ", note=" + note + "]";
    }

}

因为要序列化对象,所以需要实现Serializable接口,表明它能够序列化,serialVersionUID代表的是序列化的版本编号

使用RedisTemplate保存Role对象:

public class RoleTest {

    public static void main(String[] args) {

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);

        Role role = new Role();
        role.setId(1L);
        role.setRolename("role_name-1");
        role.setNote("note_1");

        redisTemplate.opsForValue().set("role_1", role);

        Role role1 = (Role) redisTemplate.opsForValue().get("role_1");

        System.out.println(role1);
    }

}

控制台输出的结果如下:

Role [id=1, rolename=role_name-1, note=note_1]

猜你喜欢

转载自blog.csdn.net/winfredzen/article/details/80336847