我是靠谱客的博主 醉熏枕头,最近开发中收集的这篇文章主要介绍springboot连接redis一、导包二、配置yml文件三、编写redis工具类,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

一、导包

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

        <!--工具包-->
         <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.11.1</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.10</version>
        </dependency>

二、配置yml文件

连接单个redis

spring:
  redis:
    #数据库索引,默认为0
    database: 0
    host: 192.168.139.128
    port: 6379
    password: 123456
    #连接超时时间 毫秒
    timeout: 30000
    lettuce:
       pool:
        #最大连接数 默认为8
        max-active: 8
        #连接池最大阻塞等待时间(使用负数表示没有限制) 默认-1
        max-wait: -1
        #连接池中最大的空闲连接 默认为8
        max-idle: 8
        #连接池最小空闲连接 默认为0
        min-idle: 0         

连接redis集群

redis集群搭建可以查看:https://javazhong.blog.csdn.net/article/details/126237889

spring:
  redis:
    #数据库索引,默认为0
    database: 0
    #连接超时时间 毫秒
    timeout: 30000
    cluster:
       nodes: 
          - 192.168.139.128:7000
          - 192.168.139.128:7001
          - 192.168.139.129:7000
          - 192.168.139.129:7001
    password: 123456      
    lettuce:
       pool:
        #最大连接数 默认为8
        max-active: 8
        #连接池最大阻塞等待时间(使用负数表示没有限制) 默认-1
        max-wait: -1
        #连接池中最大的空闲连接 默认为8
        max-idle: 8
        #连接池最小空闲连接 默认为0
        min-idle: 0  

三、编写redis工具类

1、编写工具类和bean

public class RedisService {
    private static final Logger log = LoggerFactory.getLogger(RedisService.class);
    private final RedisTemplate redisTemplate;

    public boolean expire(String key, long time) {
        try {
            if (time > 0L) {
                this.redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }

            return true;
        } catch (Exception var5) {
            log.error(var5.getMessage(), var5);
            return false;
        }
    }

    public long getExpire(String key) {
        return this.redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    public boolean hasKey(String key) {
        try {
            return this.redisTemplate.hasKey(key);
        } catch (Exception var3) {
            log.error(var3.getMessage(), var3);
            return false;
        }
    }

    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                this.redisTemplate.delete(key[0]);
            } else {
                this.redisTemplate.delete(CollUtil.toList(key));
            }
        }

    }

    public Object get(String key) {
        return key == null ? null : this.redisTemplate.opsForValue().get(key);
    }

    public <T> T getCacheObject(String key) {
        ValueOperations<String, T> operation = this.redisTemplate.opsForValue();
        return operation.get(key);
    }

    public String getStr(String key) {
        return key == null ? null : String.valueOf(this.redisTemplate.opsForValue().get(key));
    }

    public boolean set(String key, Object value) {
        try {
            this.redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return false;
        }
    }

    public boolean setStr(String key, Object value) {
        return this.set(key, value);
    }

    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0L) {
                this.redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                this.set(key, value);
            }

            return true;
        } catch (Exception var6) {
            log.error(var6.getMessage(), var6);
            return false;
        }
    }

    public boolean setStr(String key, String value, long time) {
        return this.set(key, value, time);
    }

    public long incr(String key, long delta) {
        if (delta < 0L) {
            throw new RuntimeException("递增因子必须大于0");
        } else {
            return this.redisTemplate.opsForValue().increment(key, delta);
        }
    }

    public long decr(String key, long delta) {
        if (delta < 0L) {
            throw new RuntimeException("递减因子必须大于0");
        } else {
            return this.redisTemplate.opsForValue().increment(key, -delta);
        }
    }

    public Object hget(String key, String item) {
        return this.redisTemplate.opsForHash().get(key, item);
    }

    public Map<Object, Object> hmget(String key) {
        return this.redisTemplate.opsForHash().entries(key);
    }

    public boolean hmset(String key, Map<String, Object> map) {
        try {
            this.redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return false;
        }
    }

    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            this.redisTemplate.opsForHash().putAll(key, map);
            if (time > 0L) {
                this.expire(key, time);
            }

            return true;
        } catch (Exception var6) {
            log.error(var6.getMessage(), var6);
            return false;
        }
    }

    public boolean hset(String key, String item, Object value) {
        try {
            this.redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception var5) {
            log.error(var5.getMessage(), var5);
            return false;
        }
    }

    public boolean hset(String key, String item, Object value, long time) {
        try {
            this.redisTemplate.opsForHash().put(key, item, value);
            if (time > 0L) {
                this.expire(key, time);
            }

            return true;
        } catch (Exception var7) {
            log.error(var7.getMessage(), var7);
            return false;
        }
    }

    public void hdel(String key, Object... item) {
        this.redisTemplate.opsForHash().delete(key, item);
    }

    public boolean hHasKey(String key, String item) {
        return this.redisTemplate.opsForHash().hasKey(key, item);
    }

    public double hincr(String key, String item, double by) {
        return this.redisTemplate.opsForHash().increment(key, item, by);
    }

    public double hdecr(String key, String item, double by) {
        return this.redisTemplate.opsForHash().increment(key, item, -by);
    }

    public Set<Object> sGet(String key) {
        try {
            return this.redisTemplate.opsForSet().members(key);
        } catch (Exception var3) {
            log.error(var3.getMessage(), var3);
            return null;
        }
    }

    public boolean sHasKey(String key, Object value) {
        try {
            return this.redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return false;
        }
    }

    public long sSet(String key, Object... values) {
        try {
            return this.redisTemplate.opsForSet().add(key, values);
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return 0L;
        }
    }

    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = this.redisTemplate.opsForSet().add(key, values);
            if (time > 0L) {
                this.expire(key, time);
            }

            return count;
        } catch (Exception var6) {
            log.error(var6.getMessage(), var6);
            return 0L;
        }
    }

    public long sGetSetSize(String key) {
        try {
            return this.redisTemplate.opsForSet().size(key);
        } catch (Exception var3) {
            log.error(var3.getMessage(), var3);
            return 0L;
        }
    }

    public long setRemove(String key, Object... values) {
        try {
            Long count = this.redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return 0L;
        }
    }

    public List<Object> lGet(String key, long start, long end) {
        try {
            return this.redisTemplate.opsForList().range(key, start, end);
        } catch (Exception var7) {
            log.error(var7.getMessage(), var7);
            return null;
        }
    }

    public <T> List<T> getCacheList(String key) {
        return this.redisTemplate.opsForList().range(key, 0L, -1L);
    }

    public long lGetListSize(String key) {
        try {
            return this.redisTemplate.opsForList().size(key);
        } catch (Exception var3) {
            log.error(var3.getMessage(), var3);
            return 0L;
        }
    }

    public Object lGetIndex(String key, long index) {
        try {
            return this.redisTemplate.opsForList().index(key, index);
        } catch (Exception var5) {
            log.error(var5.getMessage(), var5);
            return null;
        }
    }

    public boolean lSet(String key, Object value) {
        try {
            this.redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return false;
        }
    }

    public boolean lSet(String key, Object value, long time) {
        try {
            this.redisTemplate.opsForList().rightPush(key, value);
            if (time > 0L) {
                this.expire(key, time);
            }

            return true;
        } catch (Exception var6) {
            log.error(var6.getMessage(), var6);
            return false;
        }
    }

    public boolean lSet(String key, List<Object> values) {
        try {
            this.redisTemplate.opsForList().rightPushAll(key, values);
            return true;
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return false;
        }
    }

    public boolean lSet(String key, List<Object> values, long time) {
        try {
            this.redisTemplate.opsForList().rightPushAll(key, values);
            if (time > 0L) {
                this.expire(key, time);
            }

            return true;
        } catch (Exception var6) {
            log.error(var6.getMessage(), var6);
            return false;
        }
    }

    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            this.redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception var6) {
            log.error(var6.getMessage(), var6);
            return false;
        }
    }

    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = this.redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception var6) {
            log.error(var6.getMessage(), var6);
            return 0L;
        }
    }

    public RedisService(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}
@Configuration
public class RedisConfig {
    public RedisConfig() {
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        return redisTemplate;
    }

    @Bean
    public RedisService redisService(RedisTemplate<String, Object> redisTemplate) {
        return new RedisService(redisTemplate);
    }
}

2、在项目启动的地方进行手动导入bean

@ImportAutoConfiguration({RedisConfig.class}) 这个注解的意思就是将这个类进行自动配置

@SpringBootApplication
@ImportAutoConfiguration({RedisConfig.class})
public class CloudBaseApplication {

    public static void main(String[] args) {
        SpringApplication.run(CloudBaseApplication.class, args);
    }

}

3、创建一个controller层进行测试

@AllArgsConstructor
@RestController
public class TestController {

    @Autowired
    private RedisService redisService;

    @GetMapping("/redis")
    public void redisTest() {
        //过期时间为三秒
        redisService.set("java","redis",3);
        if(redisService.hasKey("java")){
            System.out.println(redisService.get("java"));
        }
    }
}

4、测试结果

最后

以上就是醉熏枕头为你收集整理的springboot连接redis一、导包二、配置yml文件三、编写redis工具类的全部内容,希望文章能够帮你解决springboot连接redis一、导包二、配置yml文件三、编写redis工具类所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部