SSM(Maven) 基于Spring -Cache注解整合Redis

这是基于SSM 架构整合Spring-Cache与Redis的整合(SSM整合这里就不详细介绍了大家自行在网上查阅)

1.pom.xml 引入一下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> 

2.Redis关键类,用于CRUD操作 --- RedisUtil

package cn.com.teacher.redis;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.concurrent.Callable;

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 RedisUtil 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() {
		return this.name;
	}

	@Override
	public Object getNativeCache() {
		return this.redisTemplate;
	}

	/**
	 * 从缓存中获取key
	 */
	@Override
	public ValueWrapper get(Object key) {
		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);
	}

	/**
	 * 将一个新的key保存到缓存中 先拿到需要缓存key名称和对象,然后将其转成ByteArray
	 */
	@Override
	public void put(Object key, Object value) {
		System.out.println("put key");
		final String keyf = key.toString();
		final Object valuef = value;
		//final long liveTime = 0;
		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;
	}

	/**
	 * 删除key
	 */
	@Override
	public void evict(Object key) {
		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());
			}
		});
	}

	/**
	 * 清空key
	 */
	@Override
	public void clear() {
		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) {
		return null;
	}

	@Override
	public ValueWrapper putIfAbsent(Object key, Object value) {
		return null;
	}

	@Override
	public <T> T get(Object arg0, Callable<T> arg1) {
		// TODO Auto-generated method stub
		return null;
	}

}

3.Spring整合redis配置文件---spring-redis.xml

<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:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:util="http://www.springframework.org/schema/util"
       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.1.xsd
						http://www.springframework.org/schema/context
						http://www.springframework.org/schema/context/spring-context-4.1.xsd
						http://www.springframework.org/schema/tx
						http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
						http://www.springframework.org/schema/aop 
						http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
						http://www.springframework.org/schema/util 
					    http://www.springframework.org/schema/util/spring-util-4.1.xsd
					    http://www.springframework.org/schema/cache 
					    http://www.springframework.org/schema/cache/spring-cache-4.1.xsd">
			
    <!-- 启用注解 -->
    <context:annotation-config/>
    <!-- 启动缓存注解 -->
    <cache:annotation-driven/>
    <!-- 读取redis 配置文件 --> 					
    <context:property-placeholder location="classpath*:/config/redis.properties"  ignore-unresolvable="true"/>
    <!-- 注解扫描 -->
    <context:component-scan base-package="cn.com.teacher.redis"></context:component-scan>  
    <!--设置数据池-->
    <bean id="poolConfig"  class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"></property>
        <property name="minIdle" value="${redis.minIdle}"></property>
        <property name="maxTotal" value="${redis.maxTotal}"></property>
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"></property>
    </bean>
    <!--链接redis-->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.host}"></property>
        <property name="port" value="${redis.port}"></property>
        <property name="password" value="${redis.password}"></property>
        <property name="poolConfig" ref="poolConfig"></property>
    </bean>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="connectionFactory" >
        <!--以下针对各种数据进行序列化方式的选择-->
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="hashKeySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <!--<property name="hashValueSerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>-->
    </bean>
    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">    
             <property name="caches">    
                <set>    
                    <bean class="cn.com.teacher.redis.RedisUtil">    
                         <property name="redisTemplate" ref="redisTemplate" />    
                         <property name="name" value="CacheInfo"/>    
                         <!-- User名称要在类或方法的注解中使用 -->  
                    </bean>  
                </set>    
             </property>    
    </bean> 
</beans>

4.redis.properties---redis配置相关属性文件

redis.maxIdle=300
redis.minIdle=100
redis.maxWaitMillis=3000
redis.testOnBorrow=true
redis.maxTotal=500
redis.host=127.0.0.1
redis.port=6379
redis.password=

5.springMVC配置文件中添加一下配置

 
 
<!-- 启用注解 -->
<context:annotation-config/>
<!-- 启动缓存注解 -->
<cache:annotation-driven/>

6.web.xml中添加一下代码

<context-param>
    <param-name>contextConfigLocation</param-name>
	<param-value>
            classpath:/spring-redis.xml
        </param-value>
</context-param>

7.在service对应的方法上添加以下注解用对Redis缓存清除和添加

  @Override
  @CacheEvict(value = {"getUser", "getUserById"}, allEntries = true)  //添加缓存
  public void updateUser(UserVO user) {
        userDao.updateUser(user);   
}     
    @Override
    @Cacheable(value="User",key="getUserById")//清除指定
    public UserVO getUserById(int id) {
        return userDao.getUserById(id);
    }














猜你喜欢

转载自blog.csdn.net/guokezhongdeyuzhou/article/details/80801241