SpringBoot整合redis(单机)

简单项目搭建:https://blog.csdn.net/HuanBuXingDeXingXing/article/details/109670434

一、Pom.xml引入redis相关jar

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

 此处reids版本号引用springboot指定版本

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

 二、基础配置文件配置

application-dev.yml

#开发环境配置
spring:
#redis_config
  redis:
    database: 0           # Redis数据库索引(默认为0)
    host: 10.75.13.23     # Redis服务器地址
    port: 7010            # Redis服务器连接端口
    password: 1234567890  # Redis服务器连接密码(默认为空)
    timeout: 200          # 连接超时时间(毫秒)
    jedis:
      pool:
        max-active: 200   # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1      # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 10      # 连接池中的最大空闲连接
        min-idle: 0       # 连接池中的最小空闲连接

 application.yml

#服务器端口号配置
server:
  port: 9080

#配置文件读取环境配置
spring:
  profiles:
    active: dev

 三、redis序列化及反序列化配置

package com.zx.redis.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisAutoConfig {

    //配置redisTemplate的序列化方式覆盖默认配置
    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

四、自定义redis基础操作工具类JedisUtil 

package com.zx.redis.util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;
//redis操作工具类
public final class JedisUtil {

    private JedisPool jedisPool;

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    // set方式,当key不存在时才set
    private static final String NX = "NX";
    // set方式,当key存在时才set
    private static final String XX = "XX";
    // 过期时间单位,秒
    private static final String EX = "EX";
    // 过期时间单位,毫秒
    private static final String PX = "PX";
    //过期时间
    private static final int TIMEOUT =  10000;

    // 获取Jedis实例
    public synchronized  Jedis getJedis() {
        try {
            if (jedisPool != null) {
                return jedisPool.getResource();
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //加锁
    public  long lock(String key,String value){
        long lock=0;
        Jedis j=getJedis();
        if(null!=j){
            while(lock!=1){
                lock=j.setnx(key, value);
            }
            j.expire(key, 5);
            close(j);
        }
        return lock;
    }

    //解锁
    public  void unlock(String key){
        Jedis j=getJedis();
        if(null!=j){
            j.del(key);
            close(j);
        }
    }

    // 设置值并过期时长(单位:秒)
    public  void set(String key, String value, int seconds) {
        Jedis j = getJedis();
        if (null != j) {
            j.setex(key,seconds,value);
            close(j);
        }
    }

    // 设置值并过期时长(单位:毫秒)
    public  void set(String key, String value, long time) {
        Jedis j = getJedis();
        if (null != j) {
            SetParams params = new SetParams();
            params.px(time);
            j.set(key, value,params);
            close(j);
        }
    }

    // 设置值
    public void set(String key, String value) {
        Jedis j = getJedis();
        j.set(key, value);
        close(j);
    }

    // 设置值(可选库)
    public void setDbKey(String key, String value, Integer db) {
        Jedis j = getJedis();
        if (null != db && db >= 0 && db <= 15) {
            j.select(db);
        }
        j.set(key, value);
        close(j);
    }

    // 设置值(可选库,过期时间,单位:毫秒)
    public void setDbKey(String key,String value,Integer db,long time) {
        Jedis j = getJedis();
        if (null != db && db >= 0 && db <= 15) {
            j.select(db);
        }
        j.setex(key, (int) (time%1000),value);
        close(j);
    }

    // 获取值(指定库)
    public String getDbKey(Integer db, String key) {
        String value = null;
        Jedis j = getJedis();
        if (null != db && db >= 0 && db <= 15) {
            j.select(db);
        }
        if (null != j) {
            value = j.get(key);
            close(j);
        }
        return value;
    }

    // 设置值
    public void setDbKeyLock(String key, String value, int seconds, Integer db) {
        Jedis j = getJedis();
        if (null != db && db >= 0 && db <= 15) {
            j.select(db);
        }
        j.setex(key, seconds,value);
        close(j);
    }

    // 获取值(指定库)
    public Integer getDbInteger(Integer db, String key) {
        String value = null;
        Jedis j = getJedis();
        if (null != db && db >= 0 && db <= 15) {
            j.select(db);
        }
        if (null != j) {
            value = j.get(key);
            close(j);
        }
        return null != value && !"".equals(value.trim())? Integer.parseInt(value) : null;
    }


    // 获取值
    public String get(String key) {
        String value = null;
        Jedis j = getJedis();
        if (null != j) {
            value = j.get(key);
            close(j);
        }
        return value;
    }

    // 获取值
    public Integer getInteger(String key) {
        String value = null;
        Jedis j = getJedis();
        if (null != j) {
            value = j.get(key);
            close(j);
        }
        return null != value && !"".equals(value.trim()) ? Integer.parseInt(value) : null;
    }

    public synchronized Long getIncr(String key) {
        Long value = null;
        Jedis j = getJedis();
        if (null != j) {
            value = j.incr(key);
            close(j);
        }
        return value;
    }

    //删除
    public Long remove(String key){
        Jedis j = getJedis();
        Long ret = j.del(key);
        close(j);
        return ret;
    }

    //删除
    public Long remove(Integer db,String key) {
        Jedis j = getJedis();
        if (null != db && db >= 0 && db <= 15) {
            j.select(db);
        }
        Long ret = j.del(key);
        close(j);
        return ret;
    }

    // 释放jedis资源
    public void close(final Jedis jedis) {
        if (jedis != null) {
            jedis.close();
//            jedisPool.close();
        }
    }
}

 

五、 jedisPool连接池初始化注入配置

package com.zx.redis.config;
import com.zx.redis.util.JedisUtil;
import io.lettuce.core.RedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@ConditionalOnClass(JedisUtil.class)
public class JedisAutoConfig {

    private final Logger logger = LoggerFactory.getLogger(JedisAutoConfig.class);

    @Value("${spring.redis.host}")
    private String ADDR;
    @Value("${spring.redis.port}")
    private int PORT;
    @Value("${spring.redis.password}")
    private String PASSWORD;
    @Value("${spring.redis.timeout}")
    private int TIMTOUT;
    @Value("${spring.redis.jedis.pool.max-active}")
    private int MAX_TOTAL;
    @Value("${spring.redis.jedis.pool.max-wait}")
    private int MAX_WAIT;
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int MAX_IDLE;
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int MIN_IDLE;

    //初始化jedis池
    @Bean(name = "jedisPool")
    public JedisPool jedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        // 最大连接数, 默认8个
        config.setMaxTotal(MAX_TOTAL);
        // 最大空闲连接数, 默认8个 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
        config.setMaxIdle(MAX_IDLE);
        // 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
        config.setMaxWaitMillis(MAX_WAIT);
        config.setMinIdle(MIN_IDLE);
        // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
        config.setBlockWhenExhausted(true);
        // 设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
        config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
        // 是否启用pool的jmx管理功能, 默认true
        config.setJmxEnabled(true);
        // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
        config.setTestOnBorrow(true);
        return new JedisPool(config, ADDR, PORT,TIMTOUT, PASSWORD);
    }

    //初始化我们自己自定义的jedisUtil工具类
    @Bean
    @ConditionalOnMissingBean(RedisClient.class)
    public JedisUtil jedisUtil(@Qualifier("jedisPool") JedisPool pool) {
        logger.info("初始化……Redis Client==Host={},Port={}", ADDR, PORT);
        JedisUtil jedisUtil = new JedisUtil();
        jedisUtil.setJedisPool(pool);
        return jedisUtil;
    }
}

 六、测试使用

package com.zx.redis;
import com.zx.redis.util.JedisUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class TestJedisUtil {

    @Autowired
    private JedisUtil jedisUtil;

    @Test
    void test() {
        System.out.println("redis所有库中未存放任何数据情况下:");
        printKey();

        System.out.println("redis库中存放指定数据:");
        jedisUtil.set("test1","10");
        jedisUtil.set("test2","10",5);
        jedisUtil.set("test3","10",10000L);
        jedisUtil.setDbKey("test11","存入2库",2);

        System.out.println("redis库中存放指定数据后查询:");
        printKey();
        
        sleep(2);
        System.out.println("睡眠2秒后查询:");
        printKey();
        
        sleep(3);
        System.out.println("再次睡眠3秒后查询:");
        printKey();

        jedisUtil.remove(2,"test11");
        System.out.println("移除2库中的test11后查询");
        printKey();
    }
    
    //打印key的值
    private void printKey(){
        System.out.println(jedisUtil.get("test1"));
        System.out.println(jedisUtil.get("test2"));
        System.out.println(jedisUtil.get("test3"));
        System.out.println(jedisUtil.get("test11"));
        System.out.println(jedisUtil.getDbKey(2,"test11"));
    }
    
    //睡眠指定秒数
    private void sleep(int seconds){
        try {
            Thread.sleep(seconds*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

结果展示:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值