SpringBoot 整合redis

1、依赖

<dependencies>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
		<dependency>
  			<groupId>org.slf4j</groupId>
  			<artifactId>slf4j-api</artifactId>
		  	<version>1.7.30</version>
		</dependency>
</dependencies>

2、application.properties配置

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

3、RedisConfig配置

@Configuration
@EnableCaching
public class RedisConfig {
    @Value("${spring.redis.cluster.nodes}")
    private String clusterNodes;

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

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

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

    @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.max-wait}")
    private int maxWait;

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

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

    @Bean
    public JedisPool redisPoolFactory() {   // 单机模式
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWait);
        jedisPoolConfig.setMaxTotal(maxActive);

        if (password != null) {
            return new JedisPool(jedisPoolConfig, host, port, timeout, password);
        } else {
            return new JedisPool(jedisPoolConfig, host, port);
        }
    }
}

RedisUtil封装

@Component("redis")
public class RedisUtil {
    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);
    
    @Autowired(required = false)
    private JedisPool jedisPool;
    
    @Autowired(required = false)
    private JedisCluster jedisCluster;

	/**
     * 简要说明:获取Jedis连接客户端
     *
     * @return redis.clients.jedis.Jedis
     */
	public Jedis getJedisClient() {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
        } catch (Exception e) {
            logger.error("获取Redis客户端连接失败:" + e);
        }
        if (jedis == null) {
            logger.warn("Redis客户端连接获取失败");
        }
        return jedis;
    }

    /**
     * 回收资源
     *
     * @param jedis
     * @return void
     */
    public void close(Jedis jedis) {
        try {
            if (jedis != null) {
                jedis.close();
            }
        } catch (Exception e) {
            if (jedis.isConnected()) {
                jedis.quit();
                jedis.disconnect();
            }
        }
    }

    /**
     * 简要说明:设置字符串型数据
     *
     * @param key     存储键
     * @param value   存储值
     * @param timeout 超时时间(单位:秒) 设置为0,永久存在。
     * @return void
     */
    public void setString(String key, String value, int timeout) {
        if (key == null) {
            throw new NullPointerException("Key不能为空!");
        }
        
        Jedis jedis = null;
        try {
            jedis = getJedisClient();
            jedis.set(key, value);
            if (timeout > 0) {
                jedis.expire(key, timeout);
            }
        } catch (Exception e) {
            close(jedis);
            logger.error("操作Redis失败", e);
        } finally {
            close(jedis);
        }
    }

	/**
     * 获取字符串型数据
     *
     * @param key [存储键]
     * @return String
     */
    public String getString(String key) {
        if (key == null) {
            throw new NullPointerException("Key不能为空!");
        }
        String value = null;
        Jedis jedis = null;
        try {
            jedis = getJedisClient();
            value = jedis.get(key);
        } catch (Exception e) {
            close(jedis);
            logger.error("操作Redis失败", e);
        } finally {
            close(jedis);
        }

        return value;
    }

	/**
     * 删除字符串数据
     *
     * @param key [存储键]
     */
    public void delString(String key) {
        if (key == null) {
            throw new NullPointerException("Key不能为空!");
        }

        Jedis jedis = null;
        try {
            jedis = getJedisClient();
            jedis.del(key);
        } catch (Exception e) {
            close(jedis);
            logger.error("操作Redis失败", e);
        } finally {
            close(jedis);
        }
    }

	/**
     * 判断键是否存在
     *
     * @param key
     */
    public boolean exists(String key) {
        if (key == null) {
            throw new NullPointerException("Key不能为空!");
        }
        boolean result = false;
        Jedis jedis = null;
        try {
            jedis = getJedisClient();
            result = jedis.exists(key);

        } catch (Exception e) {
            close(jedis);
            logger.error("操作Redis失败", e);
        } finally {
            close(jedis);
        }
        return result;
    }

	/**
     * 清除DB
     */
    public void flushDB() {
        Jedis jedis = null;
        try {
            jedis = getJedisClient();
            jedis.flushDB();
            logger.info("Redis缓存DB重置成功。");
        } catch (Exception e) {
            close(jedis);
            logger.error("操作Redis失败", e);
        } finally {
            close(jedis);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Little Tomato

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值