1. redis(单机版)实现spring缓存
1.1. 环境准备
使用maven搭建一套ssm框架,并创建测试类查询emp表。测试代码如下:
/** * @不开启springCache */ public static void main(String[] args) { ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml"); EmpBiz empBiz=(EmpBiz) ac.getBean("empBizImpl"); Long begin=System.currentTimeMillis(); List<Emp> empList = empBiz.findAllEmp(); System.out.println("员工数:"+empList.size()); Long end=System.currentTimeMillis(); System.out.println("花费时间:"+(end-begin)); }
结果截图:
<!-- spring版本号 --> <spring.version>4.3.3.RELEASE</spring.version> <!-- redis java开发客户端 Jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.7.4.RELEASE</version> </dependency>
2) 修改配置文件applicationContext.xml,扫描service层
3) 添加配置文件spring-redis.xml
<!-- redis连接池配置 --> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="2000" /> <property name="maxTotal" value="20000" /> <property name="minEvictableIdleTimeMillis" value="300000"></property> <property name="numTestsPerEvictionRun" value="3"></property> <property name="timeBetweenEvictionRunsMillis" value="60000"></property> <property name="maxWaitMillis" value="20000" /> <property name="testOnBorrow" value="false" /> </bean> <!-- Spring-redis连接池管理工厂 --> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="192.168.153.164" /> <property name="port" value="6379" /> <property name="poolConfig" ref="poolConfig" /> </bean> <!-- 配置redis模版 --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory" /> </bean> <!-- spring自己的缓存管理器,这里定义了缓存位置名称 ,即注解中的value --> <bean id="myCacheManager" class="org.springframework.cache.support.SimpleCacheManager"> <property name="caches"> <set> <bean class="com.aaa.util.SpringRedisCache"> <property name="redisTemplate" ref="redisTemplate" /> <property name="name" value="chenjian"/> <!-- common名称要在类或方法的注解中使用 --> </bean> </set> </property> </bean> <!-- 开启 cache注解 --> <cache:annotation-driven cache-manager="myCacheManager" proxy-target-class="true"/>
4) 创建spring cache接口的实现类SpringRedisCache
/** * @author fuyadong * @description springcache的实现类 * @company 付亚东 * 2018-1-13下午2:07:15 */ public class SpringRedisCache 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; }
6) 测试类
要在需要缓存的方法或者类上加缓存注解
@Cacheable /** * @开启springCache */ public static void main(String[] args) { ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml","spring-redis.xml"); EmpBiz empBiz=(EmpBiz) ac.getBean("empBizImpl"); Long begin=System.currentTimeMillis(); List<Emp> empList = empBiz.findAllEmp(); System.out.println("员工数:"+empList.size()); Long end=System.currentTimeMillis(); System.out.println("花费时间:"+(end-begin)); }
7) 测试效果
第一次查询
第二次查询
8) spring缓存注解@Cacheable
可以标记在一个方法上,也可以标记在一个类上。当标记在一个方法上时表示该方法是支持缓存的,当标记在一个类上时则表示该类所有的方法都是支持缓存的(value key condition)
value属性是必须指定的,其表示当前方法的返回值是会被缓存在哪个Cache上的,对应Cache的名称。其可以是一个Cache也可以是多个Cache,当需要指定多个Cache时其是一个数组。
key属性是用来指定Spring缓存方法的返回结果时对应的key的。该属性支持SpringEL表达式。当我们没有指定该属性时,Spring将使用默认策略生成key。
/** * 按照员工编号查询员工信息,juan是缓存的名称,#empno是缓存的key,返回值Emp对象是缓存的值 * @param empno * @return emp */ @Override @Cacheable(value="juan",key="#empno") public Emp selectByPrimaryKey(Short empno) { return empMapper.selectByPrimaryKey(empno); }
condition有的时候我们可能并不希望缓存一个方法所有的返回结果。通过condition属性可以实现这一功能。condition属性默认为空,表示将缓存所有的调用情形。其值是通过SpringEL表达式来指定的,当为true时表示进行缓存处理;当为false时表示不进行缓存处理,即每次调用该方法时该方法都会执行一次。如下示例表示只有当empno为偶数时才会进行缓存。
/** * 按照员工编号查询员工信息,juan是缓存的名称,#empno是缓存的key,返回值Emp对象是缓存的值 * condition="#empno%2==0"缓存工号为偶数的员工信息,奇数不缓存 * @param empno * @return emp */ @Override @Cacheable(value="juan",key="#empno",condition="#empno%2==0") public Emp selectByPrimaryKey(Short empno) { return empMapper.selectByPrimaryKey(empno); }
9) spring缓存注解@CacheEvict
是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作
/** * 按照员工编号删除员工,并清除对应的缓存 * @param empno */ @Override @CacheEvict(value="juan",key="#empno") public void deleteByPrimaryKey(Short empno) { empMapper.deleteByPrimaryKey(empno); }
10) spring缓存注解@CachePut
CachePut也可以声明一个方法支持缓存功能。与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
/** * 修改员工信息,并同步更新缓存中的员工信息 * @CachePut不管缓存中有没有,没有的话放入缓存,有的话替换缓存 */ @Override @CachePut(value="juan",key="#emp.empno") public Emp updateByPrimaryKeySelective(Emp emp) { empMapper.updateByPrimaryKey(emp); return emp; }
测试步骤,
首先不加@CachePut(value="juan",key="#emp.empno"),查询一条数据,这条数据自动缓存到redis,然后修改这条数据,再次查询数据库变化,缓存不变,查询的结果不对。
加上@CachePut(value="juan",key="#emp.empno"),再次修改同一条数据,查询发现数据库和缓存同步修改。
2. redis(集群版)实现spring缓存
2.1. 修改配置文件spring-redis.xml
<!-- redis集群配置 --> <bean id="redisClusterConfiguration" class="org.springframework.data.redis.connection.RedisClusterConfiguration"> <property name="maxRedirects" value="3"></property> <property name="clusterNodes"> <set> <bean class="org.springframework.data.redis.connection.RedisClusterNode"> <constructor-arg index="0" value="192.168.153.164"></constructor-arg> <constructor-arg index="1" value="7001"></constructor-arg> </bean> <bean class="org.springframework.data.redis.connection.RedisClusterNode"> <constructor-arg index="0" value="192.168.153.164"></constructor-arg> <constructor-arg index="1" value="7002"></constructor-arg> </bean> <bean class="org.springframework.data.redis.connection.RedisClusterNode"> <constructor-arg index="0" value="192.168.153.164"></constructor-arg> <constructor-arg index="1" value="7003"></constructor-arg> </bean> <bean class="org.springframework.data.redis.connection.RedisClusterNode"> <constructor-arg index="0" value="192.168.153.164"></constructor-arg> <constructor-arg index="1" value="7004"></constructor-arg> </bean> <bean class="org.springframework.data.redis.connection.RedisClusterNode"> <constructor-arg index="0" value="192.168.153.164"></constructor-arg> <constructor-arg index="1" value="7005"></constructor-arg> </bean> <bean class="org.springframework.data.redis.connection.RedisClusterNode"> <constructor-arg index="0" value="192.168.153.164"></constructor-arg> <constructor-arg index="1" value="7006"></constructor-arg> </bean> </set> </property> </bean> <!-- Spring-redis连接池管理工厂 --> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <constructor-arg name="poolConfig" ref="poolConfig"/> <constructor-arg name="clusterConfig" ref="redisClusterConfiguration"/> </bean>
2.2. 测试效果
1) 启动redis集群
redis-server /usr/local/redis_cluster/7001/redis.conf redis-server /usr/local/redis_cluster/7002/redis.conf redis-server /usr/local/redis_cluster/7003/redis.conf redis-server /usr/local/redis_cluster/7004/redis.conf redis-server /usr/local/redis_cluster/7005/redis.conf redis-server /usr/local/redis_cluster/7006/redis.conf
2) 清空集群中的所有key,要在主节点上操作
使用FLUSHALL命令在所有的主节点
3) 第一次查询
查看redis集群发现缓存已经存在
4) 第二次查询
后记:redis先讲这么多,后面会给大家介绍mysql数据库的主从复制和读写分离,敬请关注。
版权付亚东笔记博客所有,禁止转载!!付亚东Java笔记博客
我的笔记博客版权我的笔记博客版权