SpringBoot-Jedis缓存

添加依赖


    
      redis.clients
      jedis
      2.9.0
    
    
      com.esotericsoftware
      kryo
      4.0.0
    

KryoSerializeUtil.java

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 使用Kryo
 * 把java对象序列化和反序列化
 * 虽然所序列化和反序列化的类无需实现java.io.Serializable接口,
 * 但还是建议实现java.io.Serializable接口,避免类修改后无法反序列化
 */
public class KryoSerializeUtil {

 /**
  * 把java对象序列化成byte数组
  *
  * @param object
  * @return
  */
 public static byte[] serialize(Object object) {
 if (object == null) {
 return null;
 }
 ByteArrayOutputStream baos = null;
 Output output = null;
 try {
 Kryo kryo = new Kryo();
 baos = new ByteArrayOutputStream();
 output = new Output(baos);
 kryo.writeObject(output, object);
 output.flush();
 return baos.toByteArray();
 } finally {
 try {
 if (baos != null) baos.close();
 } catch (IOException e) {
 e.printStackTrace();
 }
 output.close();
 }
 }

 /**
  * 把byte数组反序列化得到java对象
  *
  * @param bytes
  * @param clazz
  * @return
  */
 public static  T unserialize(byte[] bytes, Class clazz) {
 if (bytes == null || bytes.length == 0) {
 return null;
 }
 Kryo kryo = new Kryo();
 Input input = new Input(bytes);
 T obj = kryo.readObject(input, clazz);
 input.close();
 return obj;
 }
}

Redis配置文件

#redis配置开始
  redis:
   database: 0 # Redis数据库索引(默认为0)
   host: localhost # Redis服务器地址
   port: 6379 # Redis服务器连接端口
   password: 941218 # Redis服务器连接密码(默认为空)
   jedis:
    pool:
     max-active: 128 # 连接池最大连接数(使用负值表示没有限制)
     max-wait: 3000 # 连接池最大阻塞等待时间(使用负值表示没有限制)
     max-idle: 128 # 连接池中的最大空闲连接
     min-idle: 0 # 连接池中的最小空闲连接
   timeout: 5000 # 连接超时时间(毫秒)
   block-when-exhausted: true # 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true

RedisConfig.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {

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

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

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

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

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

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

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

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

 @Value("${spring.redis.jedis.pool.max-wait}")
 private long maxWaitMillis;

 @Value("${spring.redis.block-when-exhausted}")
 private boolean blockWhenExhausted;

 @Bean
 public JedisPool redisPoolFactory() throws Exception {
 JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
 jedisPoolConfig.setMaxTotal(maxActive);
 jedisPoolConfig.setMaxIdle(maxIdle);
 jedisPoolConfig.setMinIdle(minIdle);
 jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
 // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
 jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
 // 是否启用pool的jmx管理功能, 默认true
 jedisPoolConfig.setJmxEnabled(true);
 JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
 return jedisPool;
 }

 /**
  * 获取数据库索引号
  * @return
  */
 public int getDatabaseIndex() {
 return this.databaseIndex;
 }

}

RedisService.java

全操作RedisUtil参考链接:https://blog.csdn.net/zhulier1124/article/details/82193182

import .KryoSerializeUtil;
import .RedisConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.Serializable;

@Service("redis")
public class RedisService {
 private static Logger LOG = LoggerFactory.getLogger("redis-service");

 @Autowired
 private RedisConfig redisConfig;

 @Autowired
 private JedisPool jedisPool;

 /**
  * 获取Jedis
  *
  * @return
  */
 private Jedis getJedis() {
 Jedis jedis = jedisPool.getResource();
 jedis.select(redisConfig.getDatabaseIndex());
 return jedis;
 }

 /**
  * set key-value with x seconds
  *
  * @param key
  * @param val
  * @param seconds
  * @return if success return "OK" or else [null]
  */
 public String set(String key, String val, int seconds) {
 LOG.info("set [{}] = [\"{}\"] with {} seconds.", key, val, seconds);
 try (Jedis jedis = getJedis()) {
 return jedis.setex(key, seconds, val);
 }
 }

 /**
  * set key-value if absent with x seconds
  *
  * @param key
  * @param val
  * @param seconds
  * @return if success return "OK" or else [null]
  */
 public String setIfAbsent(String key, String val, int seconds) {
 LOG.info("set [{}] = [\"{}\"] with {} seconds.", key, val, seconds);
 try (Jedis jedis = getJedis()) {
 return jedis.set(key, val, "nx", "ex", seconds);
 }
 }

 /**
  * get string value with key
  *
  * @param key
  * @return return result or else [null]
  */
 public String get(String key) {
 LOG.info("get string value [{}]", key);
 try (Jedis jedis = getJedis()) {
 return jedis.get(key);
 }
 }

 /**
  * set key-object with x seconds
  *
  * @param key
  * @param obj
  * @param seconds
  * @return if success return "OK" or else [null]
  */
 public  String set(String key, T obj, int seconds) {
 LOG.info("set [{}] = [\"{}\"] with {} seconds.", key, obj.toString(), seconds);
 try (Jedis jedis = getJedis()) {
 return jedis.setex(key.getBytes(), seconds, KryoSerializeUtil.serialize(obj));
 }
 }

 /**
  * set key-object if absent with x seconds
  *
  * @param key
  * @param obj
  * @param seconds
  * @return if success return "OK" or else [null]
  */
 public  String setIfAbsent(String key, T obj, int seconds) {
 LOG.info("set [{}] = [\"{}\"] with {} seconds.", key, obj.toString(), seconds);
 try (Jedis jedis = getJedis()) {
 return jedis.set(key.getBytes(), KryoSerializeUtil.serialize(obj), "nx".getBytes(), "ex".getBytes(), seconds);
 }
 }

 /**
  * get object with key
  *
  * @param key
  * @param clz
  * @return return result or else [null]
  */
 public  T get(String key, Class clz) {
 LOG.info("get object [{}]", key);
 try (Jedis jedis = getJedis()) {
 return KryoSerializeUtil.unserialize(jedis.get(key.getBytes()), clz);
 }
 }

 /**
  * delete by key
  * @param key
  * @return
  */
 public boolean delete(String key) {
 LOG.info("delete [{}]", key);
 try (Jedis jedis = getJedis()) {
 return jedis.del(key) == 1L;
 }
 }

}

注意:jedis对象需要执行close方法,否则会出现 [ redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool ] 异常

序列化反序列化,java自带版本---------------------------------------------------------

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.Serializable;

/**
 * Redis service
 * @author yk.luo
 */
@Service("redis")
public class RedisService {
 private static Logger LOG = LoggerFactory.getLogger("redis-service");

 @Autowired
 private RedisConfig redisConfig;

 @Autowired
 private JedisPool jedisPool;

 /**
  * 获取Jedis
  * @return
  */
 private Jedis getJedis() {
 Jedis jedis = jedisPool.getResource();
 jedis.select(redisConfig.getDatabaseIndex());
 return jedis;
 }

 /**
  * set key-value with x seconds
  * @param key
  * @param val
  * @param seconds
  * @return if success return "OK" or else [null]
  */
 public String set(String key, String val, int seconds) {
 LOG.info("set [{}] = [\"{}\"] with {} seconds.", key, val, seconds);
 try (Jedis jedis = getJedis()) {
 return jedis.setex(key, seconds, val);
 }
 }

 /**
  * set key-value if absent with x seconds
  * @param key
  * @param val
  * @param seconds
  * @return if success return "OK" or else [null]
  */
 public String setIfAbsent(String key, String val, int seconds) {
 LOG.info("set [{}] = [\"{}\"] with {} seconds.", key, val, seconds);
 try (Jedis jedis = getJedis()) {
 return jedis.set(key, val, "nx", "ex", seconds);
 }
 }

 /**
  * get string value with key
  * @param key
  * @return return result or else [null]
  */
 public String get(String key) {
 LOG.info("get string value [{}]", key);
 try (Jedis jedis = getJedis()) {
 return jedis.get(key);
 }
 }

 /**
  * set key-object with x seconds
  * @param key
  * @param obj
  * @param seconds
  * @return if success return "OK" or else [null]
  */
 public  String setObject(String key, T obj, int seconds) {
 LOG.info("set [{}] = [\"{}\"] with {} seconds.", key, obj.toString(), seconds);
 try (Jedis jedis = getJedis()) {
 return jedis.setex(key.getBytes(), seconds, SerializeUtils.serialize(obj));
 }
 }

 /**
  * set key-object if absent with x seconds
  * @param key
  * @param obj
  * @param seconds
  * @return if success return "OK" or else [null]
  */
 public  String setObjectIfAbsent(String key, T obj, int seconds) {
 LOG.info("set [{}] = [\"{}\"] with {} seconds.", key, obj.toString(), seconds);
 try (Jedis jedis = getJedis()) {
 return jedis.set(key.getBytes(), SerializeUtils.serialize(obj), "nx".getBytes(), "ex".getBytes(), seconds);
 }
 }

 /**
  * get object with key
  * @param key
  * @return return result or else [null]
  */
 public  T getObject(String key) {
 LOG.info("get object [{}]", key);
 try (Jedis jedis = getJedis()) {
 byte[] bytes = jedis.get(key.getBytes());
 if (bytes == null) return null;
 return SerializeUtils.unserialize(bytes);
 }
 }

 /**
  * delete by key
  * @param key
  * @return
  */
 public boolean delete(String key) {
 LOG.info("delete [{}]", key);
 try (Jedis jedis = getJedis()) {
 return jedis.del(key) == 1L;
 }
 }

}


import java.io.*;
import java.util.Objects;

/**
 * 序列化和反序列化
 * @author yk.luo
 */
public abstract class SerializeUtils {

 public static  byte[] serialize(T obj) {
 Objects.requireNonNull(obj);
 try (
 ByteArrayOutputStream bos = new ByteArrayOutputStream();
 ObjectOutputStream oos = new ObjectOutputStream(bos)
 ) {
 oos.writeObject(obj);
 return bos.toByteArray();
 } catch (IOException e) {
 e.printStackTrace();
 return null;
 }
 }

 public static  T unserialize(byte[] bytes) {
 Objects.requireNonNull(bytes);
 try (
 ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
 ObjectInputStream ois = new ObjectInputStream(bis)
 ) {
 return (T) ois.readObject();
 } catch (IOException | ClassNotFoundException e) {
 e.printStackTrace();
 return null;
 }
 }

}

序列化反序列化,java自带版本---------------------------------------------------- end

 

 

 

 

 

 

你可能感兴趣的:(Redis,SpringBoot)