spring整合redis缓存,以注解(@Cacheable、@CachePut、@CacheEvict)形式使用
maven项目中在pom.xml中依赖2个jar包,其他的spring的jar包省略:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
spring-redis.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"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-4.2.xsd"> <context:property-placeholder location="classpath:redis-config.properties" /> <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->
<cache:annotation-driven cache-manager="cacheManager" /> <!-- redis 相关配置 -->
<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> <bean id="JedisConnectionFactory" 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"/> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="JedisConnectionFactory" />
</bean> <!-- spring自己的缓存管理器,这里定义了缓存位置名称 ,即注解中的value -->
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<!-- 这里可以配置多个redis -->
<!-- <bean class="com.cn.util.RedisCache">
<property name="redisTemplate" ref="redisTemplate" />
<property name="name" value="default"/>
</bean> -->
<bean class="com.cn.util.RedisCache">
<property name="redisTemplate" ref="redisTemplate" />
<property name="name" value="common"/>
<!-- common名称要在类或方法的注解中使用 -->
</bean>
</set>
</property>
</bean> </beans>
redis-config.properties中的内容:
# Redis settings
# server IP
redis.host=127.0.0.1
# server port
redis.port=6379
# server pass
redis.pass=
# use dbIndex
redis.database=0
# 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例
redis.maxIdle=300
# 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间(毫秒),则直接抛出JedisConnectionException;
redis.maxWait=3000
# 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的
redis.testOnBorrow=true
com.cn.util.RedisCache类中的内容:
package com.cn.util; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate; public class RedisCache implements Cache{ private RedisTemplate<String, Object> redisTemplate;
private String name;
public RedisTemplate<String, Object> getRedisTemplate() {
return redisTemplate;
} public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
} public void setName(String name) {
this.name = name;
} @Override
public String getName() {
// TODO Auto-generated method stub
return this.name;
} @Override
public Object getNativeCache() {
// TODO Auto-generated method stub
return this.redisTemplate;
} @Override
public ValueWrapper get(Object key) {
// TODO Auto-generated method stub
System.out.println("get key");
final String keyf = key.toString();
Object object = null;
object = redisTemplate.execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection)
throws DataAccessException {
byte[] key = keyf.getBytes();
byte[] value = connection.get(key);
if (value == null) {
return null;
}
return toObject(value);
}
});
return (object != null ? new SimpleValueWrapper(object) : null);
} @Override
public void put(Object key, Object value) {
// TODO Auto-generated method stub
System.out.println("put key");
final String keyf = key.toString();
final Object valuef = value;
final long liveTime = 86400;
redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection)
throws DataAccessException {
byte[] keyb = keyf.getBytes();
byte[] valueb = toByteArray(valuef);
connection.set(keyb, valueb);
if (liveTime > 0) {
connection.expire(keyb, liveTime);
}
return 1L;
}
});
} private byte[] toByteArray(Object obj) {
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
oos.close();
bos.close();
}catch (IOException ex) {
ex.printStackTrace();
}
return bytes;
} private Object toObject(byte[] bytes) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
bis.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
} @Override
public void evict(Object key) {
// TODO Auto-generated method stub
System.out.println("del key");
final String keyf = key.toString();
redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection)
throws DataAccessException {
return connection.del(keyf.getBytes());
}
});
} @Override
public void clear() {
// TODO Auto-generated method stub
System.out.println("clear key");
redisTemplate.execute(new RedisCallback<String>() {
public String doInRedis(RedisConnection connection)
throws DataAccessException {
connection.flushDb();
return "ok";
}
});
} @Override
public <T> T get(Object key, Class<T> type) {
// TODO Auto-generated method stub
return null;
} @Override
public ValueWrapper putIfAbsent(Object key, Object value) {
// TODO Auto-generated method stub
return null;
} }
到了这一步,大部分人会想在web.xml的启动配置文件地方(context-param)加入了spring-redis.xml,让项目启动时加载这个配置文件吧,但是这样启动后注解不生效。
正确的做法是:web.xml中配置了servlet控制器:
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
在DispatcherServlet的初始化过程中,框架会在web应用的 WEB-INF文件夹下寻找名为spring-mvc.xml的配置文件,如果不指定的话,默认是applicationContext.xml
只需要在spring-mvc.xml文件中引入spring-redis配置文件即可,正如spring-redis.xml中的启用注解说的:<cache:annotation-driven cache-manager="cacheManager" />注解一定要声明在spring主配置文件中才会生效。
spring-mvc.xml内容,省略了spring与spring MVC整合的那部分:
<?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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.cn" /> <!-- 引入同文件夹下的redis属性配置文件 -->
<import resource="spring-redis.xml"/> </beans>
在service的实现类中:
@Service
public class UserServiceImpl implements UserService{ @Autowired
private UserBo userBo; @Cacheable(value="common",key="'id_'+#id")
public User selectByPrimaryKey(Integer id) {
return userBo.selectByPrimaryKey(id);
} @CachePut(value="common",key="#user.getUserName()")
public void insertSelective(User user) {
userBo.insertSelective(user);
} @CacheEvict(value="common",key="'id_'+#id")
public void deleteByPrimaryKey(Integer id) {
userBo.deleteByPrimaryKey(id);
}
}
spring整合redis缓存,以注解(@Cacheable、@CachePut、@CacheEvict)形式使用的更多相关文章
- 详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用
https://blog.csdn.net/u012240455/article/details/80844361 注释介绍 @Cacheable @Cacheable 的作用 主要针对方法配置,能够 ...
- Spring-Cache 注解 @Cacheable,@CachePut , @CacheEvict
1.自动生成key @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Ob ...
- 使用maven简单搭建Spring mvc + redis缓存
注:此文参考并整合了网上的文章 <spring缓存机制>:http://blog.csdn.net/sidongxue2/article/details/30516141 <配置 S ...
- SpringBoot缓存管理(二) 整合Redis缓存实现
SpringBoot支持的缓存组件 在SpringBoot中,数据的缓存管理存储依赖于Spring框架中cache相关的org.springframework.cache.Cache和org.spri ...
- Spring整合Redis&JSON序列化&Spring/Web项目部署相关
几种JSON框架用法和效率对比: https://blog.csdn.net/sisyphus_z/article/details/53333925 https://blog.csdn.net/wei ...
- springboot整合redis缓存
使用springBoot添加redis缓存需要在POM文件里引入 org.springframework.bootspring-boot-starter-cacheorg.springframewor ...
- spring boot redis 缓存(cache)集成
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- 网站性能优化小结和spring整合redis
现在越来越多的地方需要非关系型数据库了,最近网站优化,当然从页面到服务器做了相应的优化后,通过在线网站测试工具与之前没优化对比,发现有显著提升. 服务器优化目前主要优化tomcat,在tomcat目录 ...
- spring boot redis缓存JedisPool使用
spring boot redis缓存JedisPool使用 添加依赖pom.xml中添加如下依赖 <!-- Spring Boot Redis --> <dependency> ...
随机推荐
- [topcoder]TheGridDivTwo
http://community.topcoder.com/stat?c=problem_statement&pm=13628&rd=16278 标程是BFS,我用DFS,都可解. 这 ...
- C#或Net连接Oracle操作提示 Oracle 客户端 version 8.1.7 或更高版本报错
异常问题 远程连接ORCALE 服务器,而本地未安装任何ORCALE 相关客户端及ODAC .using System.Data.OracleClient;当我们用程序操作Oracle库的时候,OPE ...
- String Painter, Chengdu 2008, LA4394
题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_ ...
- Selenium入门系列5 默认不显示的下拉列表元素操作
本节课程的下拉框是那种默认隐藏,当鼠标移到菜单上下拉框才显示的.如果直接getelement会报错,提示元素不可见: so,得先让下拉列表显示出来再获取元素 用到的新知识: is_display() ...
- POJ-2029 Get Many Persimmon Trees---二维树状数组+枚举
题目链接: https://vjudge.net/problem/POJ-2029 题目大意: 有N棵树在一个n*m的田里,给出每颗树的坐标 用一个s*t的矩形去围,最多能围几棵树 思路: 用二维树状 ...
- Poj(1703),种类并查集
题目链接:http://poj.org/problem?id=1703 已经不是第一次接触种类并查集了,直到今天才搞懂. 感谢红黑联盟,感谢杰哥!!! 每个节点只要关系确定,不管是不是同一个集合里面, ...
- js 实现序列号效果实现
前端的朋友可能遇到过这样的需求,要求在页面输入一串序列号,或激活码(就像在PC正版软件中的序列号),可是HTML中并没有为我们提供类似的组件,我们来自己实现一个: 大体的思路是在表单里有一个隐藏的in ...
- 【Java-Regex】该用正则表达式却偷懒使用 indexOf 引起的BUG
留着等下写. 背景 Excel列内容,无法获取全部格式,但我们有最终的准确格式. 用准确格式去严格匹配,而不是盲人摸象. 不符合就置为空,符合就.
- JavaWeb —— JSP 总结
JSP总结 静态网页 在网站设计中,纯粹HTML(标准通用标记语言下的一个应用)格式的网页通常被称为“静态网页”,静态网页是标准的HTML文件,它的文件扩展名是.htm..html .静态网页是 ...
- this以及执行上下文概念的重新认识
在理解this的绑定过程之前,必须要先明白调用位置,调用位置指的是函数在代码中被调用的位置,而不是声明所在的位置. (ES6的箭头函数不在该范围内,它的this在声明时已经绑定了,而不是取决于调用时. ...