在项目中常常会用到redis来缓存信息,下面就是如何在Springboot中添加redis
1:在pom.xml中添加依赖
2:配置redis
3:测试使用redis
1:在pom.xml中添加依赖,为了方便测试,这里添加了测试依赖
<!--测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2:在application.yml中配置redis
spring: datasource: url: jdbc:mysql://127.0.0.1:3306/test? useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT driver-class-name: com.mysql.cj.jdbc.Driver username: root password: password #redis redis: host: 10.1.3.188 port: 6379 password: 123456
这里需要注意的是 在application.yml 中的格式,我这里粘贴代码,不知道为什么格式不是很对,yml对格式很严格,错了一点就都不行,这里我再粘贴一下我的图片
2:测试使用redis
package com.yyy.Redis; 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.RedisTemplate; import org.springframework.test.context.junit4.SpringRunner; /** * @auther YueYangyang * @date 2020/6/27 10:20 */ @RunWith(SpringRunner.class) @SpringBootTest public class RedisTest { @Autowired private RedisTemplate redisTemplate; @Test public void redis(){ redisTemplate.boundValueOps("name").set("哈哈"); System.out.println( redisTemplate.boundValueOps("name").get()); } }