添加依赖
在pom.xml文件添加redis的依赖,如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置
在application.yml
文件中添加Redis相关的配置项,如下所示:
spring:
redis:
host: 127.0.0.1
port: 6379
lettuce:
pool:
max-active: 10 # 连接池最大连接数
max-idle: 10 # 连接池最大空闲连接
min-idle: 1 # 连接池最小空闲连接
案例
1、字符串元素
@Service
public class RedisServiceImpl implements RedisService {
@Resource
private RedisTemplate redisTemplate;
public void setString(){
String key = "stringKey";
redisTemplate.opsForValue().set(key, "This is String Test");
}
public void getString(){
String key = "stringKey";
String value = (String) redisTemplate.opsForValue().get(key);
System.out.println(value);
}
}
2、List元素
@Service
public class RedisServiceImpl implements RedisService {
@Resource
private RedisTemplate redisTemplate;
public void setList(){
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
redisTemplate.opsForList().leftPushAll("ListKey", list); // 将所有List元素添加至ListKey中
redisTemplate.opsForList().leftPush("ListKey", "d"); //添加单个元素
redisTemplate.opsForList().rightPush("ListKey", "e"); //添加单个元素
}
public void getList(){
redisTemplate.opsForList().leftPop("ListKey"); //弹出一个元素
redisTemplate.opsForList().rightPop("ListKey"); //弹出一个元素
}
}
3、对象元素
@Service
public class RedisServiceImpl implements RedisService {
@Resource
private RedisTemplate redisTemplate;
public void setObject(){
Student student = new Student();
student.setName("李四");
student.setAge(12);
student.setGrade("三年级");
student.setCreatedTime(LocalDateTime.now());
redisTemplate.opsForValue().set("objectKey", student);
}
public void getObject(){
Student student = (Student) redisTemplate.opsForValue().get("objectKey");
System.out.println(student);
}
}
要将对象保存于Redis中,该对象需要能够进行序列化,如该例中的Student需要实现Serializabler接口,如下:
@Data
public class Student implements Serializable {}
4、Map元素
@Service
public class RedisServiceImpl implements RedisService {
@Resource
private RedisTemplate redisTemplate;
public void setMap(){
Map<String, String> map = new HashMap<>();
map.put("a", "1");
map.put("b", "2");
redisTemplate.opsForHash().putAll("mapKey", map);
}
public void getMap(){
String val = (String) redisTemplate.opsForHash().get("mapKey", "a");
redisTemplate.opsForHash().delete(("mapKey", "a"));
System.out.println(val);
}
}
5、Set元素
@Service
public class RedisServiceImpl implements RedisService {
@Resource
private RedisTemplate redisTemplate;
public void setSet(){
redisTemplate.opsForSet().add("setKey", "a", "b");
}
public void getSet(){
redisTemplate.opsForSet().pop("setKey");
}
}
原创文章,作者:jiafegn,如若转载,请注明出处:https://www.techlearn.cn/archives/454