1.pom配置redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.yml文件配置:
spring:
redis:
database: 0
host: 1.1.1.1
port: 6379
timeout: 2000
password:
jedis:
pool:
max-idle: 100
min-idle: 50
max-wait: 10000
3.TreeNode实体对象
import lombok.Data;
import java.util.List;
@Data
public class TreeNode {
private String id;
private String name;
private String parentId;
private List<TreeNode> children;
}
4.service实现逻辑
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class TreeStructureRedisService {
private static final String TREE_KEY_PREFIX = "tree:";
@Autowired
private StringRedisTemplate redisTemplate;
private final ObjectMapper objectMapper = new ObjectMapper();
public void saveTree(String treeId, TreeNode root) throws JsonProcessingException {
String key = TREE_KEY_PREFIX + treeId;
String jsonTree = objectMapper.writeValueAsString(root);
redisTemplate.opsForValue().set(key, jsonTree);
}
public TreeNode getTree(String treeId) throws JsonProcessingException {
String key = TREE_KEY_PREFIX + treeId;
String jsonTree = redisTemplate.opsForValue().get(key);
if (jsonTree != null) {
return objectMapper.readValue(jsonTree, TreeNode.class);
}
return null;
}
}
5.controller实现
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
@RequestMapping("/trees")
public class TreeStructureController {
@Autowired
private TreeStructureRedisService treeStructureRedisService;
@PostMapping("/{treeId}")
public String saveTree(@PathVariable String treeId, @RequestBody TreeNode root) {
try {
treeStructureRedisService.saveTree(treeId, root);
return "Tree saved successfully";
} catch (IOException e) {
return "Error saving tree: " + e.getMessage();
}
}
@GetMapping("/{treeId}")
public TreeNode getTree(@PathVariable String treeId) {
try {
return treeStructureRedisService.getTree(treeId);
} catch (IOException e) {
return null;
}
}
}