一、springboot 集成 spring-boot-starter-data-redis

本文介绍了如何在SpringBoot项目中集成Redis,包括引入SpringBoot的Redisstarter,配置Redis连接池,创建RedissonConfig和RedisConfig类,以及实现主要的Redis操作类,如设置过期时间、获取和存储数据等。
摘要由CSDN通过智能技术生成


前言

一、 springboot 版本

        <spring-boot.version>2.3.5.RELEASE</spring-boot.version>
 <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

二、引入 redis 依赖


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

三、增加配置文件

spring:
  redis:
    cluster:
      nodes: 192.168.162.235:6379,192.168.162.235:6380,192.168.162.235:6381,192.168.162.235:6382,192.168.162.235:6383,192.168.162.235:6384
      max-redirects: 3
    pool:
      #最大空闲连接
      max-idle: 8
      #最小空闲连接
      min-idle: 0
      #最大连接数,-1表示是没有限制
      max-active: 8
      #最大阻塞等待时间,-1表示没有限制
      max-wait: -1
    #连接超时时间(毫秒)
    timeout: 60000
    commandTimeout: 5000
    password: 123456
    connectionTimeout: 60000```

四、增加配置类

1、 RedissonConfig
@Configuration
public class RedissonConfig {

    @Value("${spring.redis.cluster.nodes}")
    private String[] nodes;

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

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


    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        Config config = new Config();
        ClusterServersConfig clusterServersConfig = config.useClusterServers();
        clusterServersConfig.addNodeAddress(Stream.of(nodes).map((node) -> "redis://" + node)
                        .toArray(String[]::new))
                .setConnectTimeout(connectionTimeout);
        if (StringUtils.isNotBlank(password)) {
            clusterServersConfig.setPassword(password);
        }
        return Redisson.create(config);
    }
}
2、RedisConfig
@Configuration
public class RedisConfig {

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        // om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }

    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(
            RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

五、增加操作类,主要操作 string

Setter
@Service
public class StringRedisTemplateClient {
    @Resource
   private StringRedisTemplate stringRedisTemplate;

    /**
     * 已废弃,不兼容低版本的spring-data-redis
     */
    @Deprecated
    public Boolean expire(String key, Integer seconds) {
        Boolean succeed=stringRedisTemplate.expire(key, Duration.ofSeconds(seconds));
        return succeed;
    }
   
    /**
     * 单独key的过期时间
     */
    public Boolean expire(String key, long timeout, TimeUnit unit) {
        Boolean succeed=stringRedisTemplate.expire(key, timeout,unit);
        return succeed;
    }
    
    //get,set,setex,需要调用方自己序列化value
    public String get(String key) {
        String value=stringRedisTemplate.opsForValue().get(key);
        return value;
    }
    
    public void set(String key, String value, long timeout, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    //对象或泛型版的 set,setex,get。不用自己手动序列化
    public void set(String key, Object value) {
        String jsonStr = JSONObject.toJSONString(value);
        set(key,jsonStr);
    }

    public void setex(String key, String value, Integer seconds) {
        stringRedisTemplate.opsForValue().set(key, value, Duration.ofSeconds(seconds));
    }
    public void setex(String key, String value, Long seconds) {
        stringRedisTemplate.opsForValue().set(key, value, Duration.ofSeconds(seconds));
    }

    public void setex(String key, Object value, Integer seconds) {
        String jsonStr = JSONObject.toJSONString(value);
        setex(key,jsonStr,seconds);
    }

    public long ttl(String key) {
        Long expiresIn = stringRedisTemplate.opsForValue().getOperations().getExpire(key, TimeUnit.SECONDS);
        return expiresIn;
    }

    public <T> T get(String key, Class<T> clazz) {
        String jsonStr = get(key);
        return JSONObject.parseObject(jsonStr, clazz);
    }
    
    public <T> List<T> getList(String key, Class<T> clazz) {
        String jsonStr = get(key);
        return JSONObject.parseArray(jsonStr, clazz);
    }


    /**
     * 检查某个key是否存在
     * @param key
     * @return
     */
    public boolean exist(String key) {
        String value = get(key);
        return StringUtils.isNotBlank(value);
    }
    
    public Boolean delete(String key) {
        Boolean succeed=stringRedisTemplate.delete(key);
        return succeed;
    }

    public Long incr(String key) {
        Long increment = stringRedisTemplate.opsForValue().increment(key);
        return increment;
    }
}

总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值