Redis下载安装https://blog.csdn.net/weixin_51882166/article/details/127889515
导入坐标
新建项目模块:
(如果不使用Spring Initializr添加依赖,则需要手动添加依赖项)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置Redis
修改文件名:
打开Redis服务器,查看参数:
在yml文件里配置信息:
spring:
redis:
host: localhost
port: 6379
Redis接口
在测试类里测试:
测试set方法:
package spring_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;
import org.springframework.data.redis.core.ValueOperations;
@SpringBootTest
class SpringRedisApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void set() {
ValueOperations ops= redisTemplate.opsForValue();
ops.set("name","lucy");
}
}
@Autowired自动装配RedisTemplate(提供各种数据类型的API)。
执行在DesktopManager后查询:
获取键值并打印在控制台上:
@Test
void get() {
ValueOperations ops= redisTemplate.opsForValue();
Object name=ops.get("name");
System.out.println(name);
}
控制台:
测试放入Hash:
@Test
void hset() {
HashOperations ops = redisTemplate.opsForHash();
ops.put("info","A","a");
}
得到放入的Hash值:
@Test
void hget() {
HashOperations ops = redisTemplate.opsForHash();
Object val = ops.get("info", "A");
System.out.println(val);
}
控制台显示:
SpringBoot整合Redis:
pom.xml导入对应redis的starter;
配置;
提供操作Redis接口对象RedisTemplate;
ops*:获取各种数据类型操作接口。