实现步骤
- 搭建SpringBoot工程。
- 引入redis起步依赖。
- 配置redis相关属性。
- 注入RedisTemplate模板。
- 编写测试方法。
搭建SpringBoot工程
起步依赖
pom文件中默认就添加了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置文件
application.yml文件(前提是对应IP已经启用了redis)
spring:
redis:
host: 192.168.0.103
port: 6379
redis配置
systemctl stop firewall
wget https://download.redis.io/releases/redis-6.2.6.tar.gz
tar -xvf redis-6.2.6.tar.gz
cd redis-6.2.6 && make
cd src/
./redis-server
telnet 验证6379端口报错,需要修改redis.conf配置文件,protected-mode为no,且注释127.0.0.1的IP
-DENIED Redis is running in protected mode because protected mode is enabled
vi redis.conf
protected-mode no
#bind 127.0.0.1 -::1
启动
./redis-server ../redis.conf
测试
package com.yy.springboot_redis;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class SpringbootRedisApplicationTests {
// 注入模板
@Autowired
private RedisTemplate redisTemplate;
@Test
public void testSet() {
//存入数据
redisTemplate.boundValueOps("username").set("zhangyy");
}
@Test
public void testGet() {
//获取数据
Object username = redisTemplate.boundValueOps("username").get();
System.out.println(username);
}
}