Springboot使用Redis缓存

在pom.xml引入jar包

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

application-redis.properties中配置Redis连接信息

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.11.152
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=3000

在application.properties中加redis的配置信息

spring.profiles.active=redis

新建Redis缓存配置了RedisConfig

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 
 * redis配置类
 *
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.database}")
    private int database;

    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.pool.min-idle}")
    private int minIdle;

    // @Value("${spring.redis.pool.max-active}")
    // private int maxActive;

    // @Value("${spring.redis.pool.max-wait}")
    // private int maxWait;

  

 @Bean
    public JedisClient jedisClient() {
        return new JedisClient();
    }

    @Autowired
    @Qualifier("jedis.pool.config")
    JedisPoolConfig config;

    @Bean
    public JedisPool jedisPool() {
        String pw = "".equals(password) ? null : password;// 如果密码为空,需传null
        return new JedisPool(config, host, port, timeout, pw, database);
    }

    /**
     * 连接池配置
     * 
     * @Description:
     * @return
     */
    @Bean(name = "jedis.pool.config")
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        // jedisPoolConfig.setMaxWaitMillis(maxWait);
        // jedisPoolConfig.set ...
        return jedisPoolConfig;
    }
}

新建JedisClient缓存客户端类

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class JedisClient {

    @Autowired
    private JedisPool jedisPool;

    public Jedis getResource() {
        return jedisPool.getResource();
    }

    public void delete(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.del(key);
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }

    public String get(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.get(key);
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }

    public void set(String key, String value) {
        this.set(key, value, 0);
    }

    public void set(String key, String value, long seconds) {
        this.set(key, value, (int) seconds);
    }

    public void set(String key, String value, int seconds) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key, value);
            if (seconds > 0) {
                jedis.expire(key, seconds);
            }
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }

    /**
     * 设置List集合
     * 
     * @param key
     * @param list
     */

    public void setList(String key, List<?> list, long seconds) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            if (list == null || list.size() == 0) {
                jedis.set(key.getBytes(), "".getBytes());
            } else {
                jedis.set(key.getBytes(), SerializeUtil.serializeList(list));
                if (seconds > 0) {
                    jedis.expire(key, (int) seconds);
                }
            }
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }

    /**
     * 获取List集合
     * 
     * @param key
     * @return
     */

    public List<?> getList(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            byte[] data = jedis.get(key.getBytes());
            return SerializeUtil.deserializeList(data);
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }

    public boolean exists(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.exists(key);
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }

    public void expire(String key, int seconds) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.expire(key, seconds);
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }
    
    public Long incr(String key, long number) {
        return incr(key, number, 0);
    }
    
    public Long incr(String key, long number, int seconds) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            Long result = jedis.incrBy(key, number);
            if (seconds > 0) {
                jedis.expire(key, seconds);
            }
            return result;
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }
}
 

序列化工具类

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class SerializeUtil {
    
    /**
     * 单个序列化
     * @param object
     */

    public  static byte[] serialize(Object object){
        if (object==null) {
            return null;
        }
        ObjectOutputStream oos=null;
        ByteArrayOutputStream baos=null;
        byte[] bytes=null;
        try {
            baos=new ByteArrayOutputStream();
            oos=new ObjectOutputStream(baos);
            oos.writeObject(object);
            bytes=baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            close(oos);
            close(baos);
        }
        return bytes;
        
    }
    
    /**
     * 
     * 单个反序列化
     * @param bytes
     */

    public static Object deserialize(byte[] bytes){
        if (bytes==null) {
            return null;
        }
        ByteArrayInputStream bais=null;
        ObjectInputStream ois=null;
        try {
            bais=new ByteArrayInputStream(bytes);
            ois=new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            close(ois);
            close(bais);
        }
        return null;
    }
    
    /**
     * 序列号list集合
     * @param list
     */
    
    public static byte[] serializeList(List<?> list){
        if (list==null || list.size()==0) {
            return null;
        }
        ObjectOutputStream oos=null;
        ByteArrayOutputStream baos=null;
        byte[] bytes=null;
        try {
            baos=new ByteArrayOutputStream();
            oos =new ObjectOutputStream(baos);
            for (Object obj : list) {
                oos.writeObject(obj);
            }
            bytes=baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            close(oos);
            close(baos);
        }
        return bytes;
    }
    
    /**
     * 反序列化list集合
     * @param bytes
     */
    
    public  static List<?> deserializeList(byte[] bytes){
        if (bytes==null) {
            return null;
        }
        List<Object> list=new ArrayList<>();
        ByteArrayInputStream bais=null;
        ObjectInputStream ois=null;
        try {
            bais=new ByteArrayInputStream(bytes);
            ois=new ObjectInputStream(bais);
            while (bais.available()>0) {
                Object obj=ois.readObject();
                if (obj==null) {
                    break;
                }
                list.add(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            close(ois);
            close(bais);
        }
        return list;
    }
    private static void close(Closeable closeable) {
        if (closeable!=null) {
            try {
                closeable.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
    }
}
 

新建EquipmentService类

@Component
public class EquipmentService {

@Autowired
    private EquipmentRepository equipmentRepository;

@Autowired
    private JedisClient client;

@SuppressWarnings("unchecked")
    public List<Equipment> getEquiByRedis() {

        List<Equipment> list;
        if (client.getList("equipment") == null || client.getList("equipment").size() == 0) {
            List<Equipment> listEqui = equipmentRepository.findAll();

       //将listEqui已equipment键存入redis,缓存有效期是10分钟
            client.setList("equipment", listEqui, 600);
            list = (List<Equipment>) client.getList("equipment");
        }

       //根据键从缓存中获取liatEqui
        list = (List<Equipment>) client.getList("equipment");
        return list;
    }

}

运行之后可以在Redis数据库中看到以equipment为key的数据。不过list是序列化后存储的,所以是字节形式

猜你喜欢

转载自blog.csdn.net/U2133048/article/details/83177917