Spring boot 整合 redis
- 一、Spring boot 整合redis
- 1.1 启动redis
- 1.2 redis desktop manager
- 1.3 常用命令
- 二、操作
- 2.1 依赖包
- 2.2 配置
- 2.3 简单测试
- 2.4 StringRedisTemplate
一、Spring boot 整合redis
1.1 启动redis
redis-server
redis-cli
1.2 redis desktop manager
1.3 常用命令
select index
二、操作
2.1 依赖包
<!-- https:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.6.7</version>
</dependency>
2.2 配置
spring:
redis:
host: localhost
port: 6379
2.3 简单测试
- 直接使用RedisTemplate将数据存入了,但是由于序列化方式存储的数据不能通过get key获得。
package com.example.demo;
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
public class redisTest {
@Autowired
private RedisTemplate redisTemplate;
public void get(){
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("name","tom");
Object name = valueOperations.get("name");
System.out.println(name.toString());
}
}
- 存储结果
2.4 StringRedisTemplate
- StringRedisTemplate 会将数据存储到redis库中
package com.example.demo;
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.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
@SpringBootTest
public class redisTest {
@Autowired
private StringRedisTemplate redisTemplate;
@Test
public void get(){
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("age","tom");
Object name = valueOperations.get("name");
System.out.println(name.toString());
}
}
- 结果