SpringBoot基本操作(五)——SpringBoot使用Jedis整合Redis(有demo)

SpringBoot2.0笔记

(一)SpringBoot基本操作——环境搭建及项目创建(有demo)

(二)SpringBoot基本操作——使用IDEA打war包发布及测试

(三)SpringBoot基本操作——SpringBoot整合SpringDataJpa(有demo)

(四)SpringBoot基本操作——SpringBoot使用RedisTemplate整合Redis(有demo)

(五)SpringBoot基本操作——SpringBoot使用Jedis整合Redis(有demo)

(六)SpringBoot基本操作——SpringBoot使用Junit4单元测试(有demo)

(七)SpringBoot基本操作——SpringBoot整合Shiro权限管理(完整demo+界面)

 

本篇基于Springboot2.0 + Redis实现数据缓存及分库存储,上一篇主要使用官方推荐的RedisTemplate实现,这篇我主要以Jedis的方式来实现Redis的操作。这里再重复一遍,两种方式都可以实现对Redis的操作,RedisTemplate是对Jedis做了封装,官方推荐使用Redistemplate方式。

本文使用idea工具构建Springboot+SpringMvc+Thymeleaf+SpringDataJPA+MySql+Redis项目

GitHub地址:https://github.com/jwwam/springbootRedis2.git

一、Redis基本配置及工具类

还是来样子先看下项目demo的目录结构,基本的目录结构和上篇没什么差别。文末会给出pom包配置。

1.创建redis.properties配置文件

#redis配置开始
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=123456
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=1024
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=10000
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=200
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=10000
#redis配置结束
spring.redis.block-when-exhausted=true

这里我们要注意max-active,max-wait,max-idle,min-idle这几个参数版本不同写法也不一样,我这里由于引入了最新的Jedis包所以写法如上,请注意。

2.添加配置类RedisConfig.java

package com.springboot.demo.base.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@PropertySource("classpath:redis.properties")
@Slf4j
public class RedisConfig {

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

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

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

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

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

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

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

    @Bean
    public JedisPool redisPoolFactory()  throws Exception{
        log.info("JedisPool注入成功!!");
        log.info("redis地址:" + host + ":" + port);
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        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;
    }

}

3.创建RedisUtil.java工具类,注意,这是一个非常完整的Jedis操作redis的工具类,里面多数方法我都加入了分库操作,使用时注意规范就好。

package com.springboot.demo.base.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.SortingParams;

@Component
@Slf4j
public class RedisUtil{

	@Autowired
	private JedisPool jedisPool;

	/**
	 * <p>
	 * 通过key获取储存在redis中的value
	 * </p>
	 * <p>
	 * 并释放连接
	 * </p>
	 *
	 * @param key
	 * @param indexdb 选择redis库 0-15
	 * @return 成功返回value 失败返回null
	 */
	public String get(String key,int indexdb) {
		Jedis jedis = null;
		String value = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(indexdb);
			value = jedis.get(key);
			log.info(value);
		} catch (Exception e) {

			log.error(e.getMessage());
		} finally {
			returnResource(jedisPool, jedis);
		}
		return value;
	}

	/**
	 * <p>
	 * 通过key获取储存在redis中的value
	 * </p>
	 * <p>
	 * 并释放连接
	 * </p>
	 *
	 * @param key
	 * @param indexdb 选择redis库 0-15
	 * @return 成功返回value 失败返回null
	 */
	public byte[] get(byte[] key,int indexdb) {
		Jedis jedis = null;
		byte[] value = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(indexdb);
			value = jedis.get(key);
		} catch (Exception e) {

			log.error(e.getMessage());
		} finally {
			returnResource(jedisPool, jedis);
		}
		return value;
	}
	/**
	 * <p>
	 * 向redis存入key和value,并释放连接资源
	 * </p>
	 * <p>
	 * 如果key已经存在 则覆盖
	 * </p>
	 *
	 * @param key
	 * @param value
	 * @param indexdb 选择redis库 0-15
	 * @return 成功 返回OK 失败返回 0
	 */
	public String set(String key, String value,int indexdb) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(indexdb);
			return jedis.set(key, value);
		} catch (Exception e) {

			log.error(e.getMessage());
			return "0";
		} finally {
			returnResource(jedisPool, jedis);
		}
	}
	/**
	 * <p>
	 * 向redis存入key和value,并释放连接资源
	 * </p>
	 * <p>
	 * 如果key已经存在 则覆盖
	 * </p>
	 *
	 * @param key
	 * @param value
	 * @param indexdb 选择redis库 0-15
	 * @return 成功 返回OK 失败返回 0
	 */
	public String set(byte[] key, byte[] value,int indexdb) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(indexdb);
			return jedis.set(key, value);
		} catch (Exception e) {

			log.error(e.getMessage());
			return "0";
		} finally {
			returnResource(jedisPool, jedis);
		}
	}
	/**
	 * <p>
	 * 删除指定的key,也可以传入一个包含key的数组
	 * </p>
	 *
	 * @param keys 一个key 也可以使 string 数组
	 * @return 返回删除成功的个数
	 */
	public Long del(String... keys) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.del(keys);
		} catch (Exception e) {

			log.error(e.getMessage());
			return 0L;
		} finally {
			returnResource(jedisPool, jedis);
		}
	}
	/**
	 * <p>
	 * 删除指定的key,也可以传入一个包含key的数组
	 * </p>
	 * @param indexdb 选择redis库 0-15
	 * @param keys 一个key 也可以使 string 数组
	 * @return 返回删除成功的个数
	 */
	public Long del(int indexdb,String... keys) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(indexdb);
			return jedis.del(keys);
		} catch (Exception e) {

			log.error(e.getMessage());
			return 0L;
		} finally {
			returnResource(jedisPool, jedis);
		}
	}
	/**
	 * <p>
	 * 删除指定的key,也可以传入一个包含key的数组
	 * </p>
	 * @param indexdb 选择redis库 0-15
	 * @param keys 一个key 也可以使 string 数组
	 * @return 返回删除成功的个数
	 */
	public Long del(int indexdb,byte[]... keys) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(indexdb);
			return jedis.del(keys);
		} catch (Exception e) {

			log.error(e.getMessage());
			return 0L;
		} finally {
			returnResource(jedisPool, jedis);
		}
	}
	/**
	 * <p>
	 * 通过key向指定的value值追加值
	 * </p>
	 *
	 * @param key
	 * @param str
	 * @return 成功返回 添加后value的长度 失败 返回 添加的 value 的长度 异常返回0L
	 */
	public Long append(String key, String str) {
		Jedis jedis = null;
		Long res = null;
		try {
			jedis = jedisPool.getResource();
			res = jedis.append(key, str);
		} catch (Exception e) {

			log.error(e.getMessage());
			return 0L;
		} finally {
			returnResource(jedisPool, jedis);
		}
		return res;
	}

	/**
	 * <p>
	 * 判断key是否存在
	 * </p>
	 *
	 * @param key
	 * @return true OR false
	 */
	public Boolean exists(String key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.exists(key);
		} catch (Exception e) {

			log.error(e.getMessage());
			return false;
		} finally {
			returnResource(jedisPool, jedis);
		}
	}

	/**
	 * <p>
	 * 清空当前数据库中的所有 key,此命令从不失败。
	 * </p>
	 *
	 * @return 总是返回 OK
	 */
	public String flushDB() {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return jedis.flushDB();
		} catch (Exception e) {
			log.error(e.getMessage());
		} finally {
			returnResource(jedisPool, jedis);
		}
		return null;
	}

	/**
	 * <p>
	 * 为给定 key 设置生存时间,当 key 过期时(生存时间为 0 ),它会被自动删除。
	 * </p>
	 *
	 * @param key
	 * @param value
	 *            过期时间,单位:秒
	 * @return 成功返回1 如果存在 和 发生异常 返回 0
	 */
	public Long expire(String key, int value, int indexdb) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(indexdb);
			return jedis.expire(key, value);
		} catch (Exception e) {
			log.error(e.getMessage());
			return 0L;
		} finally {
			returnResource(jedisPool, jedis);
		}
	}

	/**
	 * <p>
	 * 以秒为单位,返回给定 key 的剩余生存时间
	 * </p>
	 *
	 * @param key
	 * @return 当 key 不存在时,返回 -2 。当 key 存在但没有设置剩余生存时间时,返回 -1 。否则,以秒为单位,返回 key
	 *         的剩余生存时间。 发生异常 返回 0
	 */
	public Long ttl(String key,int indexdb) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(indexdb);
			return jedis.ttl(key);
		} catch (Exception e) {

			log.error(e.getMessage());
			return 0L;
		} finally {
			returnResource(jedisPool, jedis);
		}
	}

	/**
	 * <p>
	 * 移除给定 key 的生存时间,将这个 key 从『易失的』(带生存时间 key )转换成『持久的』(一个不带生存时间、永不过期的 key )
	 * </p>
	 *
	 * @param key
	 * @return 当生存时间移除成功时,返回 1 .如果 key 不存在或 key 没有设置生存时间,返回 0 , 发生异常 返回 -1
	 */
	public Long persist(String key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			return j
评论 34
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值