基于SpringBoot 2.X整合Jedis

基于SpringBoot 2.X整合Jedis

说明:本文旨在整理SpringBoot 2.X整合Jedis基础功能,如有问题请指出


一. 基于redis.properties配置文件整合

基于redis.properties配置文件整合采用单例模式读取redis配置文件形式,用静态代码块初始化JedisPool,此时成员变量由配置文件读取,且需要声明为static(若采用注解形式读取,则在初始化JedisPool时成员变量尚未初始化,因此获取不到成员变量的值)

  1. redis.properties文件配置
spring.redis.database = 0      # Redis数据库索引(默认为0)
spring.redis.host = 10.0.9.6   # Redis服务器地址
spring.redis.port = port       # Redis服务器连接端口
spring.redis.timeout = 10000   # Redis连接超时时间
spring.redis.jedis.pool.maxActive = 5000   # 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.maxWait = 10000    # 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.maxIdle = 5000     # 连接池中的最大空闲连接
spring.redis.jedis.pool.minIdle = 0        # 连接池中的最小空闲连接
  1. JedisConfig配置
@Configuration
@EnableCaching
public class JedisConfig implements InitializingBean {
    private static Logger logger = LoggerFactory.getLogger(JedisConfig.class);

    private static String host = PropertiesUtil.getInstance().getVaule("spring.redis.host").trim();

    private static String port = PropertiesUtil.getInstance().getVaule("spring.redis.port").trim();

    private static String maxActive = PropertiesUtil.getInstance().getVaule("spring.redis.jedis.pool.maxActive").trim();

    private static String maxWait = PropertiesUtil.getInstance().getVaule("spring.redis.jedis.pool.maxWait").trim();

    private static String maxIdle = PropertiesUtil.getInstance().getVaule("spring.redis.jedis.pool.maxIdle").trim();

    // 成功标识
    private static final int REDIS_SUCCESS = 1;

    // 失败标识
    private static final int REDIS_FAILED = -1;

    // 实例-单例模式
    private static JedisConfig jedisConfig;

    // ShardedJedisPool池
    private static ShardedJedisPool pool;

    static {
        initJedisPool();
    }

    /**
     * 获取客户端实例
     */
    public synchronized static JedisConfig getInstance() {
        if (jedisConfig == null) {
            jedisConfig = new JedisConfig();
        }
        return jedisConfig;
    }

    /**
     * 初始化jedis连接池
     */
    private static void initJedisPool() {
        // 创建jedis池配置实例
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

        // 设连接池最大连接数
        jedisPoolConfig.setMaxTotal(Integer.parseInt(maxActive));

        // 连接池中的最大空闲连接
        jedisPoolConfig.setMaxIdle(Integer.parseInt(maxIdle));

        // 连接池最大阻塞等待时间
        jedisPoolConfig.setMaxWaitMillis(Long.valueOf(maxWait));

        // #jedis调用borrowObject方法时,是否进行有效检查
        jedisPoolConfig.setTestOnBorrow(Boolean.valueOf(true));

        // #jedis调用returnObject方法时,是否进行有效检查
        jedisPoolConfig.setTestOnReturn(Boolean.valueOf(true));

        List<JedisShardInfo> jdsInfoList = new ArrayList<JedisShardInfo>(2);

        JedisShardInfo jedisShardInfo = new JedisShardInfo(host, port);
        jdsInfoList.add(jedisShardInfo);

        pool = new ShardedJedisPool(jedisPoolConfig, jdsInfoList, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);
    }


    /**
     * @param key
     * @param message
     * @return boolean
     * @Description: 保存String信息
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public Integer saveMessage(String key, String message) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key)) {
                return REDIS_FAILED;
            }

            // 从jedis池中获取一个jedis实例
            jedis = pool.getResource();
            jedis.set(key, message);

            return REDIS_SUCCESS;

        } catch (Exception e) {
            logger.error("保存String信息异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                pool.returnResource(jedis);
        }
        return REDIS_FAILED;
    }

    /**
     * @param key
     * @param message
     * @param expire
     * @return
     * @Description: 保存String信息(生命周期单位秒)
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public Integer saveMessage(String key, String message, int expire) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key)) {
                return REDIS_FAILED;
            }

            // 从jedis池中获取一个jedis实例
            jedis = pool.getResource();
            jedis.set(key, message);
            jedis.expire(key, expire);

            return REDIS_SUCCESS;

        } catch (Exception e) {
            logger.error("保存String信息(生命周期单位秒)异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                pool.returnResource(jedis);
        }
        return REDIS_FAILED;
    }

    /**
     * @param key
     * @param message
     * @return
     * @Description: 保存byte[]信息
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public Integer saveMessage(String key, byte[] message) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key)) {
                return REDIS_FAILED;
            }

            // 从jedis池中获取一个jedis实例
            jedis = pool.getResource();
            jedis.set(key.getBytes(), message);

            return REDIS_SUCCESS;

        } catch (Exception e) {
            logger.error("保存byte[]信息异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                pool.returnResource(jedis);
        }
        return REDIS_FAILED;
    }


    /**
     * @param key
     * @param value
     * @Description: 保存对象(序列化)
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public Integer saveSerializeMessage(String key, Object value) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
                return REDIS_FAILED;
            }

            byte[] val = SerializeUtil.serialize(value);

            // 从jedis池中获取一个jedis实例
            jedis = pool.getResource();
            jedis.set(key.getBytes(), val);

            return REDIS_SUCCESS;

        } catch (Exception e) {
            logger.error("保存对象(序列化)异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                pool.returnResource(jedis);
        }
        return REDIS_FAILED;
    }

    /**
     * @param key
     * @return
     * @Description: 获取String对象类型值
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public String getMessage(String key) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key)) {
                return null;
            }

            // 从jedis池中获取一个jedis实例
            jedis = pool.getResource();

            // 获取jedis实例后可以对redis服务进行一系列的操作
            String value = jedis.get(key);

            return value;

        } catch (Exception e) {
            logger.error("获取String对象类型值异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                pool.returnResource(jedis);
        }
        return null;
    }

    /**
     * @param key
     * @return
     * @Description: 获取对象(序列化)
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public Object getSerializeMessage(String key) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key)) {
                return null;
            }

            // 从jedis池中获取一个jedis实例
            jedis = pool.getResource();


            if (StringUtils.isEmpty(jedis.get(key))) {
                return null;
            }

            // 获取jedis实例后可以对redis服务进行一系列的操作
            byte[] value = jedis.get(key.getBytes());
            Object data = SerializeUtil.unSerialize(value);

            return data;

        } catch (Exception e) {
            logger.error("获取对象(序列化)异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                pool.returnResource(jedis);
        }
        return null;
    }

    /**
     * @param key
     * @return
     * @Description: 通过key删除数据
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public Integer deleteByKey(String key) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key)) {
                return REDIS_FAILED;
            }

            // 从jedis池中获取一个jedis实例
            jedis = pool.getResource();
            jedis.del(key);

            return REDIS_SUCCESS;

        } catch (Exception e) {
            logger.error("通过key删除数据异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                pool.returnResource(jedis);
        }
        return REDIS_FAILED;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 用户初始化Jedis时打印redis配置信息
        logger.info("****************正在启动Redis****************");
        logger.info("******Redis-Url:" + host + ":" + port + "******");
        logger.info("********************************************");
    }
}
  1. 启动测试
@RestController
public class UserController {

    @RequestMapping("/testCache")
    public String testCache() {
        String cache = "This have no one";
        if (JedisConfig.getInstance().getSerializeMessage("testJedis") == null) {
            JedisConfig.getInstance().saveSerializeMessage("testJedis", "This is testCache");
        } else {
            cache = JedisConfig.getInstance().getSerializeMessage("testJedis").toString();
        }
        return cache;
    }

第一次访问:
在这里插入图片描述
第二次访问:
在这里插入图片描述

二. 基于application.yml配置文件整合

基于SpringBoot 2.X版本,这里的max-wait和timeout参数需要带上单位ms,采用注解的形式读取application.yml里面的redis配置信息,注意需要在初始化连接池时在ShardedJedisPool上加上@Bean注解,这样才能在JedisAPi里去注入

  1. application.yml文件配置
spring:
  redis:
    database: 0       # Redis数据库索引(默认为0)
    host: 10.0.9.6    # Redis服务器地址
    port: 6379        # Redis服务器连接端口
    timeout: 10000ms  # Redis连接超时时间
    jedis:
      pool:
        max-active: 5000  # 连接池最大连接数(使用负值表示没有限制)
        max-wait: 1000ms  # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 5000    # 连接池中的最大空闲连接
        min-idle: 0       # 连接池中的最小空闲连接
  1. JedisConfig2配置
@Configuration
@EnableCaching
public class JedisConfig2 implements InitializingBean {
    private static Logger logger = LoggerFactory.getLogger(JedisConfig2.class);

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

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

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

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

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


    /**
     * 初始化jedis连接池
     */
    @Bean
    public ShardedJedisPool jedisPoolConfig() {
        // 创建jedis池配置实例
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

        // 设连接池最大连接数
        jedisPoolConfig.setMaxTotal(Integer.parseInt(maxActive));

        // 连接池中的最大空闲连接
        jedisPoolConfig.setMaxIdle(Integer.parseInt(maxIdle));

        // 连接池最大阻塞等待时间
        jedisPoolConfig.setMaxWaitMillis(Long.valueOf(maxWait.substring(0, maxWait.length() - 2)));

        // #jedis调用borrowObject方法时,是否进行有效检查
        jedisPoolConfig.setTestOnBorrow(Boolean.valueOf(true));

        // #jedis调用returnObject方法时,是否进行有效检查
        jedisPoolConfig.setTestOnReturn(Boolean.valueOf(true));

        List<JedisShardInfo> jdsInfoList = new ArrayList<JedisShardInfo>(2);

        JedisShardInfo jedisShardInfo = new JedisShardInfo(host, port);
        jdsInfoList.add(jedisShardInfo);

        ShardedJedisPool pool = new ShardedJedisPool(jedisPoolConfig, jdsInfoList, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);
        return pool;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.info("****************正在启动Redis****************");
        logger.info("******Redis-Url:" + host + ":" + port + "******");
        logger.info("********************************************");
    }
}
  1. JedisApi配置
@Component
public class JedisApi {
    private static Logger logger = LoggerFactory.getLogger(JedisApi.class);

    // 成功标识
    private static final int REDIS_SUCCESS = 1;

    // 失败标识
    private static final int REDIS_FAILED = -1;

    @Autowired
    private ShardedJedisPool jedisPool;

    /**
     * @param key
     * @param message
     * @return boolean
     * @Description: 保存String信息
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public Integer saveMessage(String key, String message) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key)) {
                return REDIS_FAILED;
            }

            // 从jedis池中获取一个jedis实例
            jedis = jedisPool.getResource();
            jedis.set(key, message);

            return REDIS_SUCCESS;

        } catch (Exception e) {
            logger.error("保存String信息异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                jedisPool.returnResource(jedis);
        }
        return REDIS_FAILED;
    }

    /**
     * @param key
     * @param message
     * @param expire
     * @return
     * @Description: 保存String信息(生命周期单位秒)
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public Integer saveMessage(String key, String message, int expire) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key)) {
                return REDIS_FAILED;
            }

            // 从jedis池中获取一个jedis实例
            jedis = jedisPool.getResource();
            jedis.set(key, message);
            jedis.expire(key, expire);

            return REDIS_SUCCESS;

        } catch (Exception e) {
            logger.error("保存String信息(生命周期单位秒)异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                jedisPool.returnResource(jedis);
        }
        return REDIS_FAILED;
    }

    /**
     * @param key
     * @param message
     * @return
     * @Description: 保存byte[]信息
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public Integer saveMessage(String key, byte[] message) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key)) {
                return REDIS_FAILED;
            }

            // 从jedis池中获取一个jedis实例
            jedis = jedisPool.getResource();
            jedis.set(key.getBytes(), message);

            return REDIS_SUCCESS;

        } catch (Exception e) {
            logger.error("保存byte[]信息异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                jedisPool.returnResource(jedis);
        }
        return REDIS_FAILED;
    }


    /**
     * @param key
     * @param value
     * @Description: 保存对象(序列化)
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public Integer saveSerializeMessage(String key, Object value) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
                return REDIS_FAILED;
            }

            byte[] val = SerializeUtil.serialize(value);

            // 从jedis池中获取一个jedis实例
            jedis = jedisPool.getResource();
            jedis.set(key.getBytes(), val);

            return REDIS_SUCCESS;

        } catch (Exception e) {
            logger.error("保存对象(序列化)异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                jedisPool.returnResource(jedis);
        }
        return REDIS_FAILED;
    }

    /**
     * @param key
     * @return
     * @Description: 获取String对象类型值
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public String getMessage(String key) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key)) {
                return null;
            }

            // 从jedis池中获取一个jedis实例
            jedis = jedisPool.getResource();

            // 获取jedis实例后可以对redis服务进行一系列的操作
            String value = jedis.get(key);

            return value;

        } catch (Exception e) {
            logger.error("获取String对象类型值异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                jedisPool.returnResource(jedis);
        }
        return null;
    }

    /**
     * @param key
     * @return
     * @Description: 获取对象(序列化)
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public Object getSerializeMessage(String key) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key)) {
                return null;
            }

            // 从jedis池中获取一个jedis实例
            jedis = jedisPool.getResource();


            if (StringUtils.isEmpty(jedis.get(key))) {
                return null;
            }

            // 获取jedis实例后可以对redis服务进行一系列的操作
            byte[] value = jedis.get(key.getBytes());
            Object data = SerializeUtil.unSerialize(value);

            return data;

        } catch (Exception e) {
            logger.error("获取对象(序列化)异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                jedisPool.returnResource(jedis);
        }
        return null;
    }

    /**
     * @param key
     * @return
     * @Description: 通过key删除数据
     * @author SLy
     * @date 2018-12-19 19:49
     */
    public Integer deleteByKey(String key) {
        ShardedJedis jedis = null;
        try {
            if (StringUtils.isEmpty(key)) {
                return REDIS_FAILED;
            }

            // 从jedis池中获取一个jedis实例
            jedis = jedisPool.getResource();
            jedis.del(key);

            return REDIS_SUCCESS;

        } catch (Exception e) {
            logger.error("通过key删除数据异常", e);
            e.printStackTrace();
        } finally {
            // 释放对象池,即获取jedis实例使用后要将对象还回去
            if (jedis != null)
                jedisPool.returnResource(jedis);
        }
        return REDIS_FAILED;
    }
}
  1. 启动测试
@RestController
public class UserController {

    @Autowired
    private JedisApi jedisApi;

    @RequestMapping("/testCache")
    public String testCache() {
        String cache = "This have no one";
        if (jedisApi.getSerializeMessage("testJedis2") == null) {
            jedisApi.saveSerializeMessage("testJedis2", "This is testCache");
        } else {
            cache = jedisApi.getSerializeMessage("testJedis2").toString();
        }
        return cache;
    }
}

第一次访问:
在这里插入图片描述
第二次访问:
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值