spring集成redis

spring集成redis总思路

 1. 导入对应的依赖
 2. 在spring的配制文件中启用缓存注解功能,编写redis.properties的配置信息
 3. 将redis的数据配(JedisPoolConfig)、连接池工厂(JedisConnectionFactory)、
 	redis模板(RedisTemplate)交给spring管理及在配制文件文件中创建对应的bean。
 4.编写缓存处理类,实现cache接口
 5.启用spring自己的管理器,用来管理自己创建的缓存类(RedisCache)。

目录结构

spring集成redis_第1张图片

对应的jar坐标(注意版本问题)

        
            redis.clients
            jedis
            2.9.0
        

        
            org.springframework.data
            spring-data-redis
            1.8.6.RELEASE
        

对应的配置文件



    


    
    
        
        
        
        
    

    
    
        
        
        
        
        
        
        
        
        
        
    


    
    
        
        
            
        
        
            
        
        
            
        
        
            
        
        
        
    

    
   

    
    
        
            
                
                
                
                    
                    
                    
                
            
        
    

    

自己实现的缓存类

package com.dcy.utils;

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;

import java.io.*;
import java.util.concurrent.Callable;

public class RedisCache 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;
    }

    public String getName() {
        // TODO Auto-generated method stub
        return this.name;
    }

    public Object getNativeCache() {
        // TODO Auto-generated method stub
        return this.redisTemplate;
    }

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

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

    public void evict(Object key) {
        // TODO Auto-generated method stub
        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());
            }
        });
    }

    public void clear() {
        // TODO Auto-generated method stub
        System.out.println("clear key");
        redisTemplate.execute(new RedisCallback() {
            public String doInRedis(RedisConnection connection)
                    throws DataAccessException {
                connection.flushDb();
                return "ok";
            }
        });
    }

    public  T get(Object key, Class type) {
        // TODO Auto-generated method stub
        return null;
    }

    public  T get(Object o, Callable callable) {
        return null;
    }


    public ValueWrapper putIfAbsent(Object key, Object value) {
        // TODO Auto-generated method stub
        return null;
    }

}

 
  

对应的service


@Service
public class UserServiceImpl implements UserService{
 
	@Autowired
	private UserBo userBo;
 	/*
 		#id就是对应的参数
 	*/
	@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)