|
package com.example.redisnearby.service;
import com.example.redisnearby.dto.NearbyUserDTO;
import com.example.redisnearby.entity.UserLocation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
@RequiredArgsConstructor
public class NearbyService {
private final RedisTemplate<String, Object> redisTemplate;
@Value("${nearby.redis-key}")
private String locationKey;
@Value("${nearby.default-radius}")
private Double defaultRadius;
@Value("${nearby.max-radius}")
private Double maxRadius;
/**
* 更新用户位置(上报位置)
*
* @param userLocation 用户位置信息
*/
public void updateLocation(UserLocation userLocation) {
// 参数校验
if (userLocation.getLongitude() == null || userLocation.getLatitude() == null) {
throw new IllegalArgumentException("经纬度不能为空");
}
// 校验经纬度范围
if (userLocation.getLongitude() < -180 || userLocation.getLongitude() > 180 ||
userLocation.getLatitude() < -90 || userLocation.getLatitude() > 90) {
throw new IllegalArgumentException("经纬度范围不合法");
}
// 使用 GEOADD 命令添加位置
// Redis 内部使用 Sorted Set 存储,score 是经纬度编码后的值
Long added = redisTemplate.opsForGeo().add(
locationKey,
new Point(userLocation.getLongitude(), userLocation.getLatitude()),
userLocation.getUserId()
);
// 可选:存储用户额外信息(用户名、头像等)
String userInfoKey = "user:info:" + userLocation.getUserId();
redisTemplate.opsForHash().put(userInfoKey, "username", userLocation.getUsername());
redisTemplate.opsForHash().put(userInfoKey, "avatar", userLocation.getAvatar());
redisTemplate.opsForHash().put(userInfoKey, "updateTime", System.currentTimeMillis());
// 设置过期时间(例如7天未更新则删除)
redisTemplate.expire(userInfoKey, 7, TimeUnit.DAYS);
redisTemplate.expire(locationKey, 7, TimeUnit.DAYS);
log.info("用户 [{}] 更新位置成功: ({}, {})",
userLocation.getUserId(),
userLocation.getLongitude(),
userLocation.getLatitude()
);
}
/**
* 搜索附近的人(圆形范围)
*
* @param longitude 中心点经度
* @param latitude 中心点纬度
* @param radius 半径(米)
* @param limit 返回数量限制
* @return 附近用户列表
*/
public List<NearbyUserDTO> findNearbyUsers(Double longitude, Double latitude,
Double radius, Integer limit) {
// 参数校验和默认值处理
if (radius == null || radius <= 0) {
radius = defaultRadius;
}
// 限制最大搜索范围,防止性能问题
radius = Math.min(radius, maxRadius);
if (limit == null || limit <= 0) {
limit = 20; // 默认返回20个
}
// 构建圆心和距离
Circle circle = new Circle(
new Point(longitude, latitude),
new Distance(radius, Metrics.METERS)
);
// 构建查询参数
RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs
.newGeoRadiusArgs()
.includeDistance() // 包含距离信息
.includeCoordinates() // 包含坐标信息
.sortAscending() // 按距离升序
.limit(limit); // 限制数量
// 执行 GEORADIUS 命令
GeoResults<RedisGeoCommands.GeoLocation<Object>> results =
redisTemplate.opsForGeo().radius(locationKey, circle, args);
List<NearbyUserDTO> nearbyUsers = new ArrayList<>();
if (results == null || results.getContent().isEmpty()) {
return nearbyUsers;
}
// 处理结果
for (GeoResult<RedisGeoCommands.GeoLocation<Object>> result : results) {
String userId = (String) result.getContent().getName();
Point point = result.getContent().getPoint();
Distance distance = result.getDistance();
// 查询用户详细信息
String userInfoKey = "user:info:" + userId;
String username = (String) redisTemplate.opsForHash().get(userInfoKey, "username");
String avatar = (String) redisTemplate.opsForHash().get(userInfoKey, "avatar");
NearbyUserDTO dto = NearbyUserDTO.builder()
.userId(userId)
.username(username != null ? username : "用户" + userId)
.avatar(avatar)
.distance(distance.getValue()) // 距离(米)
.longitude(point.getX())
.latitude(point.getY())
.build();
nearbyUsers.add(dto);
}
return nearbyUsers;
}
/**
* 搜索附近的人(使用 GEOSEARCH,Redis 6.2+ 推荐)
* 功能更强大,支持按成员搜索
*/
public List<NearbyUserDTO> findNearbyUsersByMember(String userId, Double radius, Integer limit) {
// 限制范围
if (radius == null || radius <= 0) {
radius = defaultRadius;
}
radius = Math.min(radius, maxRadius);
if (limit == null || limit <= 0) {
limit = 20;
}
// 使用 GEOSEARCH 命令(需要 Redis 6.2+)
// 注意:Spring Data Redis 可能需要使用 execute 方法直接执行命令
Distance distance = new Distance(radius, Metrics.METERS);
// 构建参数
RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs
.newGeoRadiusArgs()
.includeDistance()
.includeCoordinates()
.sortAscending()
.limit(limit);
// 以指定用户为中心搜索
GeoResults<RedisGeoCommands.GeoLocation<Object>> results =
redisTemplate.opsForGeo().radius(
locationKey,
userId,
distance,
args
);
return convertToDTO(results);
}
/**
* 计算两个用户之间的距离
*/
public Double getDistance(String userId1, String userId2) {
Distance distance = redisTemplate.opsForGeo()
.distance(locationKey, userId1, userId2, Metrics.METERS);
return distance != null ? distance.getValue() : null;
}
/**
* 删除用户位置
*/
public void removeLocation(String userId) {
redisTemplate.opsForGeo().remove(locationKey, userId);
redisTemplate.delete("user:info:" + userId);
log.info("删除用户 [{}] 的位置信息", userId);
}
/**
* 获取用户当前位置
*/
public Point getUserLocation(String userId) {
List<Point> points = redisTemplate.opsForGeo().position(locationKey, userId);
return (points != null && !points.isEmpty()) ? points.get(0) : null;
}
// 辅助方法:转换结果
private List<NearbyUserDTO> convertToDTO(
GeoResults<RedisGeoCommands.GeoLocation<Object>> results) {
List<NearbyUserDTO> list = new ArrayList<>();
if (results == null) return list;
for (GeoResult<RedisGeoCommands.GeoLocation<Object>> result : results) {
String userId = (String) result.getContent().getName();
Point point = result.getContent().getPoint();
Distance distance = result.getDistance();
String userInfoKey = "user:info:" + userId;
String username = (String) redisTemplate.opsForHash().get(userInfoKey, "username");
String avatar = (String) redisTemplate.opsForHash().get(userInfoKey, "avatar");
list.add(NearbyUserDTO.builder()
.userId(userId)
.username(username != null ? username : "用户" + userId)
.avatar(avatar)
.distance(distance.getValue())
.longitude(point.getX())
.latitude(point.getY())
.build());
}
return list;
}
}
|