1.导入pom文件
<!-- 整合redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.单元测试
import com.caxs.app.WebApplication;
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.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.concurrent.TimeUnit;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes= WebApplication.class)
/**
* 图像识别单元测试
*/
public class RedisTest {
@Autowired
private StringRedisTemplate redisTemplate;
@Test
public void setRedis() {
//缓存中最常用的方法
redisTemplate.opsForValue().set("first","siwei");
//设置缓存过期时间为30 单位:秒
//关于TimeUnit下面有部分源码截图
redisTemplate.opsForValue().set("second","siweiWu",30, TimeUnit.SECONDS);
System.out.println("存入缓存成功");
}
@Test
public void setRedis2() {
//缓存中最常用的方法
ValueOperations<String, String> stringStringValueOperations = redisTemplate.opsForValue();
stringStringValueOperations.set("hello","1");
stringStringValueOperations.increment("hello",1);
System.out.println(stringStringValueOperations.get("hello"));
}
@Test
public void getRedis(){
String first = redisTemplate.opsForValue().get("first");
String second = redisTemplate.opsForValue().get("second");
System.out.println("取出缓存中first的数据是:"+first);
System.out.println("取出缓存中second的数据是:"+second);
}
@Test
public void delRedis() {
//根据key删除缓存
Boolean first1 = redisTemplate.delete("first");
System.out.println("是否删除成功:"+first1);
}
}