本文共 3348 字,大约阅读时间需要 11 分钟。
在现代社交场景中,好友功能已经成为必备的一部分。用户之间的好友关系通常包括关注、取关、共同关注等多种操作。这些功能如果单纯依靠数据库来实现,虽然简单,但在复杂场景下却难以高效处理。比如,如何快速查询两个用户的共同关注列表,就变得颇为棘手。
我们采用MySQL和Redis的方式结合使用,这样既能存储结构化的数据,又能高效处理集合操作。MySQL主要存储用户的基本信息和关注状态,而Redis通过其built-in的集合操作来管理用户间的关注关系。
Redis的Sets数据类型提供了完善的集合操作,包括添加成员、移除成员、查询成员、统计成员数、判断成员以及查询交集等功能。这些操作在处理好友关系时效率非常高。
通过Redis的SINTER操作,我们可以快速得到两个用户的共同关注列表。具体步骤如下:
package com.zjq.seckill.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.StringRedisSerializer;@Configurationpublic class RedisTemplateConfiguration { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); template.setValueSerializer(new StringRedisSerializer()); template.setKeySerializer(new StringRedisSerializer()); return template; }} org.springframework.boot spring-boot-starter-data-redis com.zjq commons 1.0-SNAPSHOT
通过上述实现,我们可以轻松完成以下操作:
@RestControllerpublic class FollowController { @Resource private FollowService followService; @Resource private HttpServletRequest request; @PostMapping("/{followUserId}") public ResultInfo follow(@PathVariable Integer followUserId, @RequestParam int isFollowed, String access_token) { return followService.follow(followUserId, isFollowed, access_token, request.getServletPath()); }} @Servicepublic class FollowService { @Resource private FollowMapper followMapper; @Resource private RedisTemplate redisTemplate; @Resource private RestTemplate restTemplate; @Value("${service.name.ms-oauth-server}") private String oauthServerName; @Value("${service.name.ms-diners-server}") private String dinersServerName; public ResultInfo follow(Integer followUserId, int isFollowed, String access_token, String path) { // 业务逻辑详见代码 return resultInfo; } private void addToRedisSet(Integer dinerId, Integer followUserId) { redisTemplate.opsForSet().add(RedisKeyConstant.following.getKey() + dinerId, followUserId); redisTemplate.opsForSet().add(RedisKeyConstant.followers.getKey() + followUserId, dinerId); }} 通过Redis和MySQL的结合,我们成功实现了高效的好友关系管理。这种设计既保证了数据的高效操作,又保持了系统的可扩展性。未来,我们可以进一步优化查询性能,并引入更多的功能如用户通知和好友排名。
转载地址:http://iiqfk.baihongyu.com/