Springboot简单使用RedisTemplate
没有在Redis的可以查看:docker安装redis及图形化界面的使用
1.导入依赖:这里我主要用的是redis+mybatis-plus
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- mybatis plus 代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.在application.properties文件中配置数据源和redis相关配置
spring.datasource.url=jdbc:mysql://localhost:3306/eshop?serverTimezone=UTC&characterEncoding=UTF-8&useUnicode=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
#redis配置需要datasource数据源
spring.redis.host=192.168.137.136
spring.redis.port=6379
在springboot测试环境中:
//操作k-v都是字符串类型的
@Autowired
private StringRedisTemplate stringRedisTemplate;
//操作k-v都是对象对象的
@Autowired
private RedisTemplate redisTemplate;
/**
* stringRedisTemplate.opsForValue() 操作字符串的
* stringRedisTemplate.opsForList() 操作列表的
* stringRedisTemplate.opsForSet() 操作集合的
* stringRedisTemplate.opsForHash() 操作散列的
* stringRedisTemplate.opsForZset() 操作有序集合的
*/
@Test
void test01() {
//添加数据到redis库中
//stringRedisTemplate.opsForValue().append("msg","helloworld1");
//获得redis中的数据
String msg = stringRedisTemplate.opsForValue().get("msg");
System.out.println(msg);
}
这里我用的Redis Derktop Mannger图像化界面: