SpringBoot整合Redis缓存-JedisPool使用

文章目录

    • Redis缓存-JedisPool使用
      • 1. 添加依赖pom.xml中添加如下依赖
      • 2. 配置application.yml文件
      • 3.JedisPool的使用
      • 4. 测试注入

Redis缓存-JedisPool使用

1. 添加依赖pom.xml中添加如下依赖


        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
            <version>2.1.8.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>redis.clientsgroupId>
            <artifactId>jedisartifactId>
            <version>2.9.0version>
        dependency>

2. 配置application.yml文件

spring:
  # 添加redis配置
  redis:
    host: Redis服务器地址
    port: 6379 # 默认端口
    password: # 默认为空
    database: # 默认为0
    timeout: 30000
    jedis:
      pool:
        #最大连接数
        max-active: 200
        #最大阻塞等待时长
        max-wait: -1
        #连接池最大空闲连接
        max-idle: 50
        #连接池最小空闲连接
        min-idle: 0
        # 提高对象池的可靠性和稳定性
        testOnBorrow: true
        testOnReturn: true

3.JedisPool的使用

package com.sky.config;/*
 *@title: RedisCacheConfiguration
 *@description:
 *@author: 小辰
 *@version: 1.0
 *@create: 2023/9/21 1:13
 */
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

@Configuration
@EnableCaching
@Data
public class RedisCacheConfiguration extends CachingConfigurerSupport {

    Logger logger = LoggerFactory.getLogger(RedisCacheConfiguration.class);

    @Value("${spring.redis.host}")
    private String host;//
    @Value("${spring.redis.port}")
    private int port;//
    @Value("${spring.redis.database}")
    private int database;//
    @Value("${spring.redis.timeout}")
    private int timeout;//
    @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 maxWait;//

    @Bean
    public JedisPool redisPoolFactory() {
        logger.info("JedisPool注入成功!!");
        logger.info("redis地址:" + host + ":" + port);
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWait);

        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);

        return jedisPool;
    }

}

4. 测试注入

@Autowired
JedisPool jedisPool;

String uuid = UUID.randomUUID().toString();
logger.info("jedisPool uuid : " + uuid);
try (Jedis jedis = jedisPool.getResource()) {
	jedis.setex(uuid, 1000, user.getUsername());
}				
   

结束!!!

你可能感兴趣的:(SprinBoot,redis,spring,boot,缓存,redis)