springboot之redis

一、简介

redis是一种非关系型数据库,它的数据结构是key-value的存储形式;能够支持多种类型的数据存储,如:string/list/map/object...等。springboot自然也对它进行了整合,我们只需要添加依赖和配置即可。

二、依赖

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

三、配置

这里我们配置了redis的IP/端口等,以及连接池的配置。连接池的开启需要引入apache的commons-pool2项目,配置前检查依赖是否存在。如果没有,那么需要添加。

# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0

四、RedisTemplate增删改查

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增
     */
    public void saveValue(){
        redisTemplate.opsForValue().set("name", "lay");
    }
    /**
     * 查询
     */
    public void getValue(){
        Object value = redisTemplate.opsForValue().get("name");
        System.out.println(value);
    }

    /**
     * 删除
     */
    public void delValue(){
        redisTemplate.delete("name");
    }

    /**
     * 更新
     */
    public void updateValue(){
        redisTemplate.opsForValue().set("name", "marry");
    }

以上代码,我们注入了RedisTemplate。springboot自动配置机制,会自动将connectionFactory注入到RedisTemplate生成Bean实例,所以我们直接注入使用即可。

猜你喜欢

转载自www.cnblogs.com/lay2017/p/8951307.html