springboot整合redis入门教程

第一步:创建一下springboot项目

第二步:导入如下依赖:

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

其中,前者是redis的依赖,后者是单元测试依赖

第三步:添加配置

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

由于本地安装的redis没有设置密码,所以注释密码一栏,否则启动会报错,其他配置因为是保持默认值,所以也注释掉

第四步:编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisApplicationTests {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void contextLoads() {
        redisTemplate.opsForValue().set("aaa", "111");
        System.out.println(redisTemplate.opsForValue().get("aaa"));
    }
}

第五步:执行单元测试代码

控制台结果如下:

111

redis客户端查看结果如下:

127.0.0.1:6379> get aaa

"111"

 

至此,使用springboot整合redis进行数据存取的入门案例已经完毕

 

 问题:

如何实现将一张参数表存入缓存中?

 

我的思考:

1、 首先需要连接数据库

2、 创建实体类

3、 使用redis的hash数据结构,将查询结果刷到缓存中

 

posted @ 2021-04-04 15:19  Java精进之路  阅读(233)  评论(0编辑  收藏  举报