Java(五):Spring Boot 集成Redis - 基础操作

旧城等待, 2024-03-16 22:46 40阅读 0赞

引入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. <version>2.1.3.RELEASE</version>
  5. </dependency>

配置文件

  1. spring:
  2. redis:
  3. database: 0
  4. host: 127.0.0.1
  5. port: 6379
  6. password: 123456

源码

在这里插入图片描述

在这里插入图片描述

  1. package com.example.demo.service.impl;
  2. import com.example.demo.entity.User;
  3. import com.example.demo.service.UserService;
  4. import org.springframework.data.redis.core.HashOperations;
  5. import org.springframework.data.redis.core.StringRedisTemplate;
  6. import org.springframework.stereotype.Service;
  7. import javax.annotation.Resource;
  8. import java.util.*;
  9. /**
  10. * (User)表服务实现类
  11. */
  12. @Service("userService")
  13. public class UserServiceImpl implements UserService {
  14. private static final String KEY = "user";
  15. @Resource
  16. private StringRedisTemplate stringRedisTemplate;
  17. /**
  18. * 新增数据
  19. *
  20. * @param user 实例对象
  21. * @return 实例对象
  22. */
  23. @Override
  24. public Map<String, Object> insert(User user) {
  25. HashOperations<String, String, Object> hashOperations = this.stringRedisTemplate.opsForHash();
  26. hashOperations.put(KEY, "id", UUID.randomUUID().toString());
  27. hashOperations.put(KEY, "name", user.name);
  28. hashOperations.put(KEY, "gender", user.gender.toString());
  29. hashOperations.put(KEY, "height", user.height.toString());
  30. hashOperations.put(KEY, "weight", user.weight.toString());
  31. hashOperations.put(KEY, "country", user.country);
  32. hashOperations.put(KEY, "createTime", new Date().toString());
  33. Set<String> keys = hashOperations.keys(KEY);
  34. Map<String, Object> map = new HashMap<>();
  35. for (String key : keys) {
  36. map.put(key, hashOperations.get(KEY, key));
  37. }
  38. return map;
  39. }
  40. }

发表评论

表情:
评论列表 (有 0 条评论,40人围观)

还没有评论,来说两句吧...

相关阅读