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

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

1.pom.xml 引入一下redis的依赖包

  
             org.springframework.data  
            spring-data-redis  
             1.6.1.RELEASE  
           
            
             redis.clients  
            jedis  
            2.7.3  
         

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 redisTemplate;
	private String name;

	public RedisTemplate getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate 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() {
			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() {
			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() {
			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() {
			public String doInRedis(RedisConnection connection) throws DataAccessException {
				connection.flushDb();
				return "ok";
			}
		});
	}

	@Override
	public  T get(Object key, Class type) {
		return null;
	}

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

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

} 
  

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


			
    
    
    
    
     					
    
    
      
    
    
        
        
        
        
        
    
    
    
        
        
        
        
    

    
        
        
            
        
        
            
        
        
            
        
        
    
        
                 
                    
                        
                             
                             
                           
                      
                    
                 
     

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配置文件中添加一下配置

 
  



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


    contextConfigLocation
	
            classpath:/spring-redis.xml
        

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














你可能感兴趣的:(Java开发)