springboot+redis实现将树形结构存储到redis
1.pom配置redis
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
2.yml文件配置:
spring:redis:database: 0host: 1.1.1.1port: 6379timeout: 2000password:jedis:pool:max-idle: 100min-idle: 50max-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:";@Autowiredprivate StringRedisTemplate redisTemplate;private final ObjectMapper objectMapper = new ObjectMapper();/*** 存储树形结构到 Redis* @param treeId 树形结构的唯一标识* @param root 树的根节点* @throws JsonProcessingException JSON 处理异常*/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);}/*** 从 Redis 中获取树形结构* @param treeId 树形结构的唯一标识* @return 树的根节点* @throws JsonProcessingException JSON 处理异常*/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 {@Autowiredprivate TreeStructureRedisService treeStructureRedisService;/*** 保存树形结构到 Redis* @param treeId 树形结构的唯一标识* @param root 树的根节点* @return 操作结果信息*/@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();}}/*** 从 Redis 中获取树形结构* @param treeId 树形结构的唯一标识* @return 树的根节点*/@GetMapping("/{treeId}")public TreeNode getTree(@PathVariable String treeId) {try {return treeStructureRedisService.getTree(treeId);} catch (IOException e) {return null;}}
}