Spring集成Redis示例

原创 2016年08月31日 15:37:45

本文章从头开始介绍Spring集成Redis的示例。


Eclipse工程结构

如下图为我的示例工程的结构图,采用Maven构建。其中需要集成Spring,因此需要beans.xml文件配置spring的依赖注入,redis.properties配置连接服务器的配置信息。
这里写图片描述
其中工程中beans.xml和redis.properties文件直接放在了根目录,有需要的读者可以放到resource目录中。

POM依赖

如下为示例POM依赖,Spring集成redis需要依赖的包为:jedis包,spring-context模块及依赖的包,spring-data-redis模块包,spring-test包用于JUnit测试,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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test</groupId>
    <artifactId>JavaTest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>JavaTest</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.6.RELEASE</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.6.RELEASE</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.7.2.RELEASE</version>
        </dependency>
    </dependencies>
</project>

Spring配置

Spring配置文件beans.xml的配置如下:

<?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:context="http://www.springframework.org/schema/context"  
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    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">  
    <!-- 加载classpath下的Redis配置文件 -->
    <context:property-placeholder location="classpath:redis.properties" />

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>  

    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
        p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"  p:pool-config-ref="poolConfig"/>  

    <!-- spring提供的模板类 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
        <property name="connectionFactory"   ref="connectionFactory" />
    </bean>

    <bean id="userDao" class="com.redis.test.UserDao" >
        <property name="redisTemplate"   ref="redisTemplate" />  
    </bean>

</beans>

在beans.xml配置文件中,需要先加载redis.properties文件。

Redis配置信息

Redis的配置信息在redis.properties文件中配置:

# Redis地址和端口和连接密码
redis.host=localhost
redis.port=6379
redis.pass=

redis.maxIdle=300
redis.testOnBorrow=true

此示例,连接Redis服务器时没有设置连接密码,因此不用填值。

Java代码

User.java

package com.redis.test;

import java.io.Serializable;

public class User implements Serializable {
    private static final long serialVersionUID = 3409768855488864675L;

    private String id;
    private String name;
    private String password;

    public User() {

    }

    public User(String id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String toString() {
        return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
    }
}

AbstractRedisBaseDao.java

package com.redis.test;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

public abstract class AbstractRedisBaseDao<K, V> {

    protected RedisTemplate<K, V> redisTemplate;

    public RedisTemplate<K, V> getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取 RedisSerializer
     */  
    protected RedisSerializer<String> getRedisSerializer() {  
        return redisTemplate.getStringSerializer();  
    }
}

IUserDao.java

package com.redis.test;

import java.util.List;

public interface IUserDao {
    /** 新增 */
    boolean add(User user);

    /** 批量新增,pipeline方式 */
    boolean add(List<User> list);

    /** 删除 */
    void delete(String key);

    /** 批量删除 */
    void delete(List<String> keys);

    /** 更新 */
    boolean update(User user);

    /** 读取 */
    User get(String keyId);
}

UserDao.java

package com.redis.test;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.Assert;

public class UserDao extends AbstractRedisBaseDao<String, User> implements IUserDao {

    public boolean add(final User user) {
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = getRedisSerializer();
                byte[] key = serializer.serialize(user.getId());// 将ID序列化成key
                byte[] value = serializer.serialize(user.getName());
                return connection.setNX(key, value);
            }
        });
        return result;
    }

    public boolean add(final List<User> list) {
        Assert.notEmpty(list);
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = getRedisSerializer();
                for (int i = 0; i < list.size(); i++) {
                    User user = list.get(i);
                    byte[] key = serializer.serialize(user.getId());// 将ID序列化成key
                    byte[] value = serializer.serialize(user.getName());
                    connection.setNX(key, value);
                }
                return true;
            }
        }, false, true);
        return result;
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public void delete(List<String> keys) {
        redisTemplate.delete(keys);
    }

    public boolean update(final User user) {
        String key = user.getId();
        if(get(key) == null) {
            throw new NullPointerException("数据行不存在,key = " + key);
        }

        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = getRedisSerializer();
                byte[] key = serializer.serialize(user.getId());// 将ID序列化成key
                byte[] value = serializer.serialize(user.getName());
                connection.set(key, value);
                return true;
            }
        });
        return result;
    }

    public User get(final String keyId) {
        User user = redisTemplate.execute(new RedisCallback<User>() {
            public User doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = getRedisSerializer();
                byte[] key = serializer.serialize(keyId);
                byte[] value = connection.get(key);
                if(value == null) {
                    return null;
                }
                String name = serializer.deserialize(value);
                return new User(keyId, name, null);
            }
        });
        return user;
    }
}

RedisTest.java(JUnit测试类)

package com.redis.test;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.util.Assert;

/**
 * junit在Spring context环境下测试
 */
@ContextConfiguration(locations={"classpath*:beans.xml"})
public class RedisTest extends AbstractJUnit4SpringContextTests {

    @Autowired
    private IUserDao userDao;

    /** 增加单个用户 */
    @Test
    public void testAddUser() {
        User user = new User("user1", "password1", null);
        boolean result = userDao.add(user);
        Assert.isTrue(result);
        System.out.println("添加结果:" + result);
    }

    /** 批量新增普通方式,5286ms */
    @Test
    public void testAddUsers1() {
        List<User> list = new ArrayList<User>();
        for (int i = 10; i < 50000; i++) {
            User user = new User();
            user.setId("user" + i);
            user.setName("password" + i);
            list.add(user);
        }
        long begin = System.currentTimeMillis();  
        for (User user : list) {  
            userDao.add(user);  
        }  
        System.out.println(System.currentTimeMillis() -  begin);
    }

    /** 批量新增pipeline方式,484ms */
    @Test
    public void testAddUsers2() {
        List<User> list = new ArrayList<User>();
        for (int i = 50000; i < 100000; i++) {
            User user = new User();
            user.setId("user" + i);
            user.setName("password" + i);
            list.add(user);
        }
        long begin = System.currentTimeMillis();  
        boolean result = userDao.add(list);
        Assert.isTrue(result);
        System.out.println(System.currentTimeMillis() -  begin);
    }

    /** 更新 */
    @Test
    public void testUpdate() {
        User user = new User();  
        user.setId("user1");  
        user.setName("new_password");  
        boolean result = userDao.update(user);  
        Assert.isTrue(result);
    }

    /** 删除 */
    @Test
    public void testDelete() {  
        String key = "user1";  
        userDao.delete(key);  
    }

    /** 批量删除 */
    @Test
    public void testDeletes() {  
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 10; i++) {
            list.add("user" + i);
        }
        userDao.delete(list);
    }

    /** 读取 */
    @Test
    public void testGetUser() {
        String id = "user1";  
        User user = userDao.get(id);
        Assert.notNull(user);
        System.out.println(user);
    }
}

使用Spring Data Redis时,遇到的几个问题

需求: 1,保存一个key-value形式的结构到redis 2,把一个对象保存成hash形式的结构到redis...
  • hotdust
  • hotdust
  • 2016年08月23日 17:33
  • 6484

Redis 缓存 + Spring 的集成示例

《整合 spring 4(包括mvc、context、orm) + mybatis 3 示例》一文简要介绍了最新版本的 Spring MVC、IOC、MyBatis ORM 三者的整合以及声明式事务处...
  • achuo
  • achuo
  • 2016年01月21日 16:54
  • 410

Redis 缓存 + Spring 的集成示例

《整合 spring 4(包括mvc、context、orm) + mybatis 3 示例》一文简要介绍了最新版本的 Spring MVC、IOC、MyBatis ORM 三者的整合以及声明式事...

详解Redis 缓存 + Spring 的集成示例

《整合 spring 4(包括mvc、context、orm) + mybatis 3 示例》一文简要介绍了最新版本的 Spring MVC、IOC、MyBatis ORM 三者的整合以及声明式事务处...

Redis 缓存 + Spring 的集成示例

1. 依赖包安装 pom.xml 加入: [html] view plain copy  print?    dependency>       g...

Redis 缓存 + Spring 的集成示例

原文: http://blog.csdn.net/defonds/article/details/48716161/ 1. 依赖包安装 pom.xml 加入: [html] ...

Redis 缓存 + Spring 的集成示例 (不错的bolg)

http://blog.csdn.net/defonds/article/details/48716161   《整合 spring 4(包括mvc、context、orm) + mybat...

Redis 缓存 + Spring 的集成示例

《整合 spring 4(包括mvc、context、orm) + mybatis 3 示例》一文简要介绍了最新版本的 Spring MVC、IOC、MyBatis ORM 三者的整合以及声明式事...

spring 集成 redis 使用例子

  • 2017年10月30日 14:21
  • 59.76MB
  • 下载

spring集成redis,配置加代码例子

  • 2017年09月17日 15:42
  • 21KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Spring集成Redis示例
举报原因:
原因补充:

(最多只允许输入30个字)