1.引入依赖
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.在配置文件中配置redis的主机地址
spring:
datasource:
username: root
password: zq0201
url: jdbc:mysql://localhost:3306/springcache
driver-class-name: com.mysql.jdbc.Driver
redis:
host: 192.168.157.132
3.当我们引入redis的启动器之后,RedisAutoConfiguration自动配置类为我们在IOC中自动注入了"redisTemplate"和"stringRedisTemplate",可以用来操作redis。直接注入要使用缓存的类使用即可
/**
* Created by Jujung
* Date : 2019/8/14 21:03
* 测试redis
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
// k-v都是对象
@Autowired
private RedisTemplate redisTemplate;
// 操作字符串 k-v都是字符串
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* String(字符串) stringRedisTemplate.opsForValue();
* List(列表) stringRedisTemplate.opsForList();
* Set(集合) stringRedisTemplate.opsForSet();
* Hash(散列) stringRedisTemplate.opsForHash();
* zset(有序集合) stringRedisTemplate.opsForZSet();
*/
@Test
public void test1(){
// 保存数据
stringRedisTemplate.opsForValue().append("msg","hello");
}
@Test
public void test2(){
// 读取数据
String msg = stringRedisTemplate.opsForValue().get("msg");
System.out.println(msg);
}
}