在項目中常常會用到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()); } }