Spring整合Redis实现数据缓存

一、什么是Redis

Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。 它支持多种类型的数据结构,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets) 与范围查询, bitmaps, hyperloglogs 和 地理空间(geospatial) 索引半径查询。 Redis 内置了 复制(replication),LUA脚本(Lua scripting), LRU驱动事件(LRU eviction),事务(transactions) 和不同级别的 磁盘持久化(persistence), 并通过 Redis哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)。

详细请看:http://www.redis.cn/

二、RedisTemplate

在Spring中,我们对Redis存储的数据进行操作时,通常使用的是RedisTemplate这个类。

我们知道,在对Redis数据进行访问时,一般情况下都是使用Redis命令进行访问,但是在Spring中,为了简化对Redis数据的访问,就产生了RedisTemplate。

RedisTemplate是一个简化Redis数据访问的一个帮助类,此类对Redis命令进行高级封装,通过此类可以调用ValueOperations和ListOperations等等方法。

三、安装Redis

Redis 使用 ANSI C 编写并且能在绝大Linux系统上运行,基于BSD协议,对OS X没有外部依赖.支持Linux 和 OS X两种系统的开发和测试,并且也推荐使用Linux部署. Redis 可以像SmartOS一样运行在Solaris系统中, 但是需要注意的是官方不支持Windos版本的Redis,但微软开发和维护着支持win-64 的Redis版本.

windows版本Redis下载链接:https://github.com/MSOpenTech/redis

下载之后按照一般安装方式默认安装就可以了,安装完之后启动Redis。

四、在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.redis</groupId>
	<artifactId>rediscache</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>rediscache Maven Webapp</name>
	<url>http://maven.apache.org</url>

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

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		  <!-- 添加Spring依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
		<!--spring单元测试依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>
		<!-- Redis 相关依赖 -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.6.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.7.3</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>rediscache</finalName>
	</build>
</project>
这里我们依赖了spring-aop和spring-aspect,主要是我们在单元测试的时候需要使用,如果不使用单元测试可以不依赖spring-aop和spring-aspect.

五、在resources文件夹下新建config.properties文件并写入Redis相关配置信息

#redis中心
#绑定的主机地址
redis.host=127.0.0.1
#指定Redis监听端口,默认端口为6379
redis.port=6379 
#授权密码(本例子没有使用)
redis.password=123456  
#最大空闲数:空闲链接数大于maxIdle时,将进行回收
redis.maxIdle=100  
#最大连接数:能够同时建立的“最大链接个数”
redis.maxActive=300  
#最大等待时间:单位ms
redis.maxWait=1000   
#使用连接时,检测连接是否成功 
redis.testOnBorrow=true 
#当客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能
redis.timeout=10000
六、在resources文件夹下新建spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<!-- 自动扫描注解的bean -->
	<context:component-scan base-package="rediscache.service" />
	
	<!-- 引入properties配置文件 --> 
	<context:property-placeholder ignore-unresolvable="true" location="classpath:config.properties" />
    
    <!-- jedis 配置 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig" >
          <property name="maxIdle" value="${redis.maxIdle}" />
          <property name="maxWaitMillis" value="${redis.maxWait}" />
          <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>

    <!-- redis服务器中心 -->
    <bean id="connectionFactory"  class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
          <property name="poolConfig" ref="poolConfig" />
          <property name="port" value="${redis.port}" />
          <property name="hostName" value="${redis.host}" />
          <!-- <property name="password" value="${redis.password}" /> -->
          <property name="timeout" value="${redis.timeout}" ></property>
    </bean >
    
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
          <property name="connectionFactory" ref="connectionFactory" />
          <property name="keySerializer" >
              <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
          </property>
          <property name="valueSerializer" >
              <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
          </property>
    </bean>
    <bean id="redisUtil" class="rediscache.utils.RedisUtil" />
</beans>

七、新建rediscache.utils包并实现RedisUtil类

package rediscache.utils;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

/**
 * @Comment
 * @Author Ron
 * @date 2017年1月13日 下午5:24:33
 */
public class RedisUtil {
	/**
	 * RedisTemplate是一个简化Redis数据访问的一个帮助类,
	 * 此类对Redis命令进行高级封装,通过此类可以调用ValueOperations和ListOperations等等方法。
	 */
	@Autowired
	private RedisTemplate<Serializable, Object> redisTemplate;

	/**
	 * 批量删除对应的value
	 * 
	 * @param keys
	 */
	public void remove(final String... keys) {
		for (String key : keys) {
			remove(key);
		}
	}

	/**
	 * 批量删除key
	 * 
	 * @param pattern
	 */
	public void removePattern(final String pattern) {
		Set<Serializable> keys = redisTemplate.keys(pattern);
		if (keys.size() > 0)
			redisTemplate.delete(keys);
	}

	/**
	 * 删除对应的value
	 * @param key
	 */
	public void remove(final String key) {
		if (exists(key)) {
			redisTemplate.delete(key);
		}
	}

	/**
	 *
	 * @param key
	 * @return
	 */
	public boolean exists(final String key) {
		return redisTemplate.hasKey(key);
	}

	/**
	 * 读取缓存
	 * @param key
	 * @return
	 */
	public Object get(final String key) {
		Object result = null;
		ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
		result = operations.get(key);
		return result;
	}
	
	/**
	 * 
	 * @Author zg
	 * @Date 2016年12月15日 上午11:28:46
	 * @param key
	 * @param hashKey
	 * @return
	 */
	public Object get(final String key, final String hashKey){
		Object result = null;
		HashOperations<Serializable,Object,Object> operations = redisTemplate.opsForHash();
		result = operations.get(key, hashKey);
		return result;
	}

	/**
	 * 写入缓存
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean set(final String key, Object value) {
		boolean result = false;
		try {
			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
			operations.set(key, value);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 
	 * @Author Ron
	 * @param key
	 * @param hashKey
	 * @param value
	 * @return
	 */
	public boolean set(final String key, final String hashKey, Object value) {
		boolean result = false;
		try {
			HashOperations<Serializable,Object,Object> operations = redisTemplate.opsForHash();
			operations.put(key, hashKey, value);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 写入缓存
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean set(final String key, Object value, Long expireTime) {
		boolean result = false;
		try {
			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
			operations.set(key, value);
			redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
八、新建rediscache.service包并实现服务测试类RedisTestServiceImpl

package rediscache.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import rediscache.utils.RedisUtil;

/**
 * @Comment
 * @Author Ron
 * @date 2017年1月13日 下午4:52:55
 */
@Component("redisTestService")
public class RedisTestServiceImpl {
	
	@Autowired
	RedisUtil redisUtil;
	
	public boolean setValue(String key,String value) {
		try {
			redisUtil.set(key, value);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	public String getValue(String key) {
		try {
			String value = (String) redisUtil.get(key);
			return value;
		} catch (Exception e) {
			return "读取缓存出错。。。";
		}
	}
}
九、编写单元测试

package rediscache;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import rediscache.service.RedisTestServiceImpl;

/**
 * @Comment
 * @Author Ron
 * @date 2017年1月13日 下午4:43:15
 */
public class testCache {
	private ClassPathXmlApplicationContext context;
	
	@Autowired
	private RedisTestServiceImpl redisTestService;
	
	@Before
	public void initConfig(){
		context = new ClassPathXmlApplicationContext("classpath:spring-mvc.xml");
		redisTestService = (RedisTestServiceImpl) context.getBean("redisTestService");
	}

	@After
	public void end(){
		if(context != null){
			context.close();
		}
	}
	
	@Test
	public void testRedisCache(){
		redisTestService.setValue("redis", "I love you redis!");
		System.out.println(redisTestService.getValue("redis"));
		System.out.println(redisTestService.getValue("redis"));
		System.out.println(redisTestService.getValue("redis"));
		System.out.println(redisTestService.getValue("redis"));
	}
}


十,测试结果






  • 8
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RonTech

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值