在项目中,我们经常需要将一些常用的数据使用缓存起来,避免频繁的查询数据库造成效率低下。spring 为我们提供了一套基于注解的缓存实现,方便我们实际的开发。我们可以扩展spring的cache接口以达到使用redis来做缓存的效果。

步骤:

1.编写一个类用于实现   org.springframework.cache.Cache  这个接口

2.编写一个类实现  org.springframework.cache.CacheManager 这个接口或继承 org.springframework.cache.support.AbstractCacheManager这个类

3.在配置文件中进行配置。

代码:

1.使用redis实现spring的cache接口 -- 数据以hash的方式存入到redis中

package com.huan.redis.springcache;

import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; /**
* 自定义redis缓存
*
* @描述
* @作者 huan
* @时间 2016年6月26日 - 下午2:14:26
*/
public class RedisCache implements Cache { private JedisPool jedisPool;
/** 缓存的过期时间,单位是秒 */
private int timeouts; public void setJedisPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
} public int getTimeouts() {
return timeouts;
} public void setTimeouts(int timeouts) {
this.timeouts = timeouts;
} private String name; public void setName(String name) {
this.name = name;
} @Override
public String getName() {
return name;
} @Override
public Object getNativeCache() {
return jedisPool;
} @Override
public ValueWrapper get(Object key) {
ValueWrapper result = null;
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String value = jedis.hget(getName(), (String) key);
if (value != null) {
result = new SimpleValueWrapper(value);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis) {
jedis.close();
}
}
return result;
} @Override
public void put(Object key, Object value) {
String cacheKey = (String) key;
String cacheValue = (String) value;
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.hset(getName(), cacheKey, cacheValue);
jedis.expire(getName(), getTimeouts());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis) {
jedis.close();
}
}
} @Override
public void evict(Object key) {
if (null != key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.hdel(getName(), (String) key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis) {
jedis.close();
}
}
}
} @Override
public void clear() {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.hdel(getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis) {
jedis.close();
}
}
}
}

2.实现自己的缓存管理器

package com.huan.redis.springcache;

import java.util.Collection;

import org.springframework.cache.Cache;
import org.springframework.cache.support.AbstractCacheManager; /**
* 继承spring的抽象缓存管理器,用于实现我们自己的缓存管理
* @描述
* @作者 huan
* @时间 2016年6月26日 - 下午2:17:15
*/
public class RedisCacheManager extends AbstractCacheManager{ private Collection<? extends RedisCache> caches; public void setCaches(Collection<? extends RedisCache> caches) {
this.caches = caches;
} @Override
protected Collection<? extends Cache> loadCaches() {
return this.caches;
} }

3.配置文件中进行配置

<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="com.huan.redis" />
<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="testWhileIdle" value="true" />
<property name="minEvictableIdleTimeMillis" value="60000" />
<property name="timeBetweenEvictionRunsMillis" value="30000" />
<property name="numTestsPerEvictionRun" value="-1" />
<property name="maxTotal" value="8" />
<property name="maxIdle" value="8" />
<property name="minIdle" value="0" />
</bean>
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg ref="jedisPoolConfig" />
<constructor-arg value="192.168.1.5" />
</bean>
<bean id="cacheManager" class="com.huan.redis.springcache.RedisCacheManager">
<property name="caches">
<set>
<bean class="com.huan.redis.springcache.RedisCache">
<property name="jedisPool" ref="jedisPool" />
<property name="name" value="usersCache" />
<property name="timeouts" value="3600" />
</bean>
<bean class="com.huan.redis.springcache.RedisCache">
<property name="jedisPool" ref="jedisPool" />
<property name="name" value="booksCache" />
<property name="timeouts" value="3600" />
</bean>
</set>
</property>
</bean>
</beans>

 注意:1. <cache:annotation-driven cache-manager="cacheManager"/>这一句用于开启spring的缓存注解

2.redis.clients.jedis.JedisPool 用于配置redis的地址和端口,默认端口是6379,如果自己的redis不是这个端口,可以选择JedisPool中适当的构造方法进行配置

4.编写业务方法 -- UserService类中比较简单,就是UserServiceImpl中方法的申明。

package com.huan.redis.service;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; /**
* 测试业务员方法
* @描述
* @作者 huan
* @时间 2016年6月26日 - 下午3:20:58
*/
@Service
public class UserServiceImpl implements UserService {
/** 将数据放入到usersCache这个缓存中,缓存的key使用spirng的spel表达式获取值 */
@Override
@Cacheable(value = "usersCache", key = "#loginName")
public String getUser(String loginName) {
System.out.println("no user cache:" + loginName);
return loginName;
}
@Override
public String getUserNoCache(String loginName) {
return getUser(loginName);
}
@Override
@Cacheable(value = "booksCache", key = "#bookId")
public String addBook(String bookId) {
System.out.println("no book cache:" + bookId);
return bookId;
}
/** 使usersCache中的缓存key为#loginName这个值的缓存失效 */
@Override
@CacheEvict(value = "usersCache", key = "#loginName")
public void evictUser(String loginName) {
System.out.println("evict cache loginName:" + loginName);
}
}

5.进行测试

spring cache整合redis的更多相关文章

  1. SpringBoot--使用Spring Cache整合redis

    一.简介 Spring Cache是Spring对缓存的封装,适用于 EHCache.Redis.Guava等缓存技术. 二.作用 主要是可以使用注解的方式来处理缓存,例如,我们使用redis缓存时, ...

  2. 【Spring】17、spring cache 与redis缓存整合

    spring cache,基本能够满足一般应用对缓存的需求,但现实总是很复杂,当你的用户量上去或者性能跟不上,总需要进行扩展,这个时候你或许对其提供的内存缓存不满意了,因为其不支持高可用性,也不具备持 ...

  3. springboot整合spring @Cache和Redis

    转载请注明出处:https://www.cnblogs.com/wenjunwei/p/10779450.html spring基于注解的缓存 对于缓存声明,spring的缓存提供了一组java注解: ...

  4. Spring Boot2 系列教程(二十九)Spring Boot 整合 Redis

    经过 Spring Boot 的整合封装与自动化配置,在 Spring Boot 中整合Redis 已经变得非常容易了,开发者只需要引入 Spring Data Redis 依赖,然后简单配下 red ...

  5. Spring优雅整合Redis缓存

    “小明,多系统的session共享,怎么处理?”“Redis缓存啊!” “小明,我想实现一个简单的消息队列?”“Redis缓存啊!” “小明,分布式锁这玩意有什么方案?”“Redis缓存啊!” “小明 ...

  6. Spring Boot(八)集成Spring Cache 和 Redis

    在Spring Boot中添加spring-boot-starter-data-redis依赖: <dependency> <groupId>org.springframewo ...

  7. SpringBoot入门系列(七)Spring Boot整合Redis缓存

    前面介绍了Spring Boot 中的整合Mybatis并实现增删改查,.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/ ...

  8. Spring Boot 整合 Redis 和 JavaMailSender 实现邮箱注册功能

    Spring Boot 整合 Redis 和 JavaMailSender 实现邮箱注册功能 开篇 现在的网站基本都有邮件注册功能,毕竟可以通过邮件定期的给用户发送一些 垃圾邮件 精选推荐

  9. 使用Spring Cache集成Redis

    SpringBoot 是为了简化 Spring 应用的创建.运行.调试.部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖 ...

随机推荐

  1. 网络游戏逆向分析-6-使用背包物品call

    网络游戏逆向分析-6-使用背包物品call 首先,大家在处理网络游戏的时候,一定得利用好发包函数,因为他就是整个网络游戏的关键. 处理办法: 这里还是直接给发包打断点来处理. 就像我们之前处理喊话函数 ...

  2. servlet请求转发于重定向

    请求的转发与重定向是Servlet控制页面跳转的主要方法,在Web应用中使用非常广泛. 一. 请求的转发 Servlet接收到浏览器端请求后,进行一定的处理,先不进行响应,而是在服务器端内部" ...

  3. scrum项目冲刺_day03总结

    摘要:今日完成任务. 1.图像识别已完成,但是较为卡顿,仍需优化 2.语音输入正在进行 3.搜索功能正在进行 总任务: 一.appUI页面(已完成) 二.首页功能: 1.图像识别功能(基本完成) 2. ...

  4. 【PHP数据结构】顺序表(数组)的相关逻辑操作

    在定义好了物理结构,也就是存储结构之后,我们就需要对这个存储结构进行一系列的逻辑操作.在这里,我们就从顺序表入手,因为这个结构非常简单,就是我们最常用的数组.那么针对数组,我们通常都会有哪些操作呢? ...

  5. Docker系类(25)- 发布镜像到DockerHub

    # step-1 注册账号 https://hub.docker.com/# step-2 在服务器尚提交我们的镜像[root@localhost WEB-INF]# docker login --h ...

  6. (原创)一步步优化业务代码之——从数据库获取DataTable并绑定到List<Class>

    一,前言 现实业务当中,有一个很常见的流程:从数据库获取数据到DataTable,然后将DataTable绑定到实体类集合上,一般是List<Class>,代码写起来也简单:遍历+赋值就可 ...

  7. Leetcode 矩阵置零

    题目描述(中等难度) 给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 .请使用 原地 算法. 进阶: 一个直观的解决方案是使用  O(mn) 的额外空间,但这 ...

  8. web带宽估算方法

    每个连接约占用10Kb的带宽,以3万总用户数和10%的在线率计算,并按照10%的冗余率,服务器总带宽=每秒总连接数*10Kbps /(1-冗余率)/1024. 带宽占用(Mbps)=30000*10% ...

  9. P7408-[JOI 2021 Final]ダンジョン 3【贪心,树状数组】

    正题 题目链接:https://www.luogu.com.cn/problem/P7408 题目大意 一个有\(n+1\)层的地牢,从\(i\)到\(i+1\)层要\(A_i\)点能量,第\(i\) ...

  10. 阿里云ECS服务器Centos中安装SQL Server(破解内存限制)

    前言 前段时间赶上阿里云618活动入手了一个低配的Linux服务器,供自己学习使用,在安装SQL Server中遇到了很多小问题,查阅很多博客结合自身遇到的问题做个总结. 安装过程 1.下载阿里云在线 ...