SpringBoot集成redis入门教程

1.新建一个springBoot web项目

具体教程可以参见此篇博文:https://blog.csdn.net/qq_37856300/article/details/86223134

2.添加spring-data依赖

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

3.在application.properties中添加配置

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址(可以在此填写远程redis服务器地址)
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=200

4.在安装目录下编辑redis配置文件redis.conf

projected-mode yes修改为projected-mode no受保护模式关闭,即可允许远程访问redis:
在这里插入图片描述

5.在linux中启动redis

输入redis-server即可启动redis

启动后输入redis-cli即可进入redis控制台

6.编写java程序

这里我用junit写了一个小的测试类,如果不了解的直接在主方法中写也是可以的,这里我使用的是StringRedisTemplate,是用来存储key和value都是String类型的,使用别的来做测试也是可以的。

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisdemoApplicationTests {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Test
    public void contextLoads() {
        stringRedisTemplate.opsForValue().set("aaa","111");
    }

}

7.运行

直接运行程序,然后去redis服务器验证一下有没有将值保存进去即可:
在这里插入图片描述

可以看到,输入key aaa可以取到value为111的值,大功告成!

猜你喜欢

转载自blog.csdn.net/qq_37856300/article/details/89603156