在Spring Boot 2中使用Redis实现String数据类型的缓存,特别是用于复杂计数功能,比如粉丝数的增加和减少,可以使用StringRedisTemplate
。下面是一个简单的示例代码:
-
添加Redis依赖:
在
pom.xml
中添加Spring Boot对Redis的支持:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
-
配置Redis连接信息:
在
application.properties
(或application.yml
)中配置Redis连接信息:spring.redis.host=your-redis-host spring.redis.port=your-redis-port spring.redis.password=your-redis-password
如果Redis没有密码,可以不配置
spring.redis.password
。 -
编写Service类实现粉丝数的增加和减少功能:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; @Service public class FanService { private final StringRedisTemplate stringRedisTemplate; @Autowired public FanService(StringRedisTemplate stringRedisTemplate) { this.stringRedisTemplate = stringRedisTemplate; } public Long increaseFansCount(String userId) { // 递增粉丝数 return stringRedisTemplate.opsForValue().increment("fans:" + userId); } public Long decreaseFansCount(String userId) { // 递减粉丝数 return stringRedisTemplate.opsForValue().decrement("fans:" + userId); } public Long getFansCount(String userId) { // 获取粉丝数 String fansCount = stringRedisTemplate.opsForValue().get("fans:" + userId); return fansCount != null ? Long.parseLong(fansCount) : 0; } }
上述代码中,使用
StringRedisTemplate
进行Redis操作,通过opsForValue()
获取String类型的操作对象,然后可以使用increment
和decrement
进行递增和递减操作,同时通过get
获取当前粉丝数。 -
Controller层调用Service:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/fans") public class FanController { private final FanService fanService; @Autowired public FanController(FanService fanService) { this.fanService = fanService; } @PostMapping("/increase/{userId}") public Long increaseFansCount(@PathVariable String userId) { return fanService.increaseFansCount(userId); } @PostMapping("/decrease/{userId}") public Long decreaseFansCount(@PathVariable String userId) { return fanService.decreaseFansCount(userId); } @GetMapping("/get/{userId}") public Long getFansCount(@PathVariable String userId) { return fanService.getFansCount(userId); } }
上述代码中,使用
@PostMapping
和@GetMapping
定义了增加、减少和获取粉丝数的接口。通过访问这些接口,可以实现对Redis中存储的粉丝数进行操作。
确保Redis服务器已启动,并根据实际情况修改配置信息和代码中的key,就可以运行这个简单的示例了。