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);
    }














發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章