广告位联系
返回顶部

SpringBoot3.0 + Redis 实现附近的人功能

java 来源:互联网 作者:佚名 发布时间:2026-11-28 22:29:19 人浏览
摘要

一、原理概述 Redis 3.2+ 版本提供了 GEO(地理位置) 数据结构,专门用于存储和查询地理位置信息。核心命令包括: 命令 功能 GEOADD 添加地理位置 GEORADIUS/GEOSEARCH 搜索指定范围内的成员 GEODIS

一、原理概述

Redis 3.2+ 版本提供了 GEO(地理位置) 数据结构,专门用于存储和查询地理位置信息。核心命令包括:

命令 功能
GEOADD 添加地理位置
GEORADIUS / GEOSEARCH 搜索指定范围内的成员
GEODIST 计算两点距离
GEOPOS 获取成员坐标

二、项目搭建

1. 创建 Spring Boot 3.0 项目

pom.xml 依赖:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"

         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0

         https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>3.0.0</version>

        <relativePath/>

    </parent>

    <groupId>com.example</groupId>

    <artifactId>redis-nearby</artifactId>

    <version>1.0.0</version>

    <name>redis-nearby</name>

    <description>Redis 附近的人功能</description>

    <properties>

        <java.version>17</java.version>

    </properties>

    <dependencies>

        <!-- Spring Boot Web -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

        <!-- Spring Data Redis -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-redis</artifactId>

        </dependency>

        <!-- Lombok -->

        <dependency>

            <groupId>org.projectlombok</groupId>

            <artifactId>lombok</artifactId>

            <optional>true</optional>

        </dependency>

        <!-- 连接池 -->

        <dependency>

            <groupId>org.apache.commons</groupId>

            <artifactId>commons-pool2</artifactId>

        </dependency>

    </dependencies>

</project>

2. 配置文件

application.yml:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

spring:

  data:

    redis:

      host: localhost

      port: 6379

      password:       # 如果有密码请填写

      database: 0

      lettuce:

        pool:

          max-active: 8

          max-idle: 8

          min-idle: 0

          max-wait: -1ms

# 自定义配置

nearby:

  redis-key: "user:location"  # Redis中存储位置的key

  default-radius: 5000        # 默认搜索半径:5公里(单位:米)

  max-radius: 50000           # 最大搜索半径:50公里

三、核心代码实现

1. 实体类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

package com.example.redisnearby.entity;

import lombok.AllArgsConstructor;

import lombok.Builder;

import lombok.Data;

import lombok.NoArgsConstructor;

/**

 * 用户位置信息

 */

@Data

@Builder

@NoArgsConstructor

@AllArgsConstructor

public class UserLocation {

    /** 用户ID */

    private String userId;

    /** 经度 */

    private Double longitude;

    /** 纬度 */

    private Double latitude;

    /** 用户名/昵称 */

    private String username;

    /** 头像URL */

    private String avatar;

    /** 更新时间戳 */

    private Long updateTime;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

package com.example.redisnearby.dto;

import lombok.AllArgsConstructor;

import lombok.Builder;

import lombok.Data;

import lombok.NoArgsConstructor;

/**

 * 附近的人DTO

 */

@Data

@Builder

@NoArgsConstructor

@AllArgsConstructor

public class NearbyUserDTO {

    /** 用户ID */

    private String userId;

    /** 用户名 */

    private String username;

    /** 头像 */

    private String avatar;

    /** 距离(米) */

    private Double distance;

    /** 经度 */

    private Double longitude;

    /** 纬度 */

    private Double latitude;

}

2. Redis配置类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

package com.example.redisnearby.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.GenericJackson2JsonRedisSerializer;

import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration

public class RedisConfig {

    @Bean

    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();

        template.setConnectionFactory(connectionFactory);

        // Key序列化

        template.setKeySerializer(new StringRedisSerializer());

        template.setHashKeySerializer(new StringRedisSerializer());

        // Value序列化

        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        template.afterPropertiesSet();

        return template;

    }

}

3. 核心Service层

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

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;

    }

}

四、Controller 接口层

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

package com.example.redisnearby.controller;

import com.example.redisnearby.dto.NearbyUserDTO;

import com.example.redisnearby.entity.UserLocation;

import com.example.redisnearby.service.NearbyService;

import com.example.redisnearby.vo.Result;

import lombok.RequiredArgsConstructor;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController

@RequestMapping("/api/nearby")

@RequiredArgsConstructor

public class NearbyController {

    private final NearbyService nearbyService;

    /**

     * 上报/更新位置

     * POST /api/nearby/location

     */

    @PostMapping("/location")

    public Result<Void> updateLocation(@RequestBody UserLocation location) {

        nearbyService.updateLocation(location);

        return Result.success();

    }

    /**

     * 搜索附近的人

     * GET /api/nearby/search?longitude=116.397&latitude=39.916&radius=5000&limit=20

     */

    @GetMapping("/search")

    public Result<List<NearbyUserDTO>> searchNearby(

            @RequestParam Double longitude,

            @RequestParam Double latitude,

            @RequestParam(required = false) Double radius,

            @RequestParam(required = false) Integer limit) {

        List<NearbyUserDTO> users = nearbyService.findNearbyUsers(longitude, latitude, radius, limit);

        return Result.success(users);

    }

    /**

     * 获取与某用户的距离

     * GET /api/nearby/distance?userId1=1001&userId2=1002

     */

    @GetMapping("/distance")

    public Result<Double> getDistance(@RequestParam String userId1, @RequestParam String userId2) {

        Double distance = nearbyService.getDistance(userId1, userId2);

        return Result.success(distance);

    }

    /**

     * 删除位置

     * DELETE /api/nearby/location/{userId}

     */

    @DeleteMapping("/location/{userId}")

    public Result<Void> removeLocation(@PathVariable String userId) {

        nearbyService.removeLocation(userId);

        return Result.success();

    }

}

统一返回结果类:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

package com.example.redisnearby.vo;

import lombok.Data;

@Data

public class Result<T> {

    private Integer code;

    private String message;

    private T data;

    public static <T> Result<T> success(T data) {

        Result<T> result = new Result<>();

        result.setCode(200);

        result.setMessage("success");

        result.setData(data);

        return result;

    }

    public static <T> Result<T> success() {

        return success(null);

    }

    public static <T> Result<T> error(String message) {

        Result<T> result = new Result<>();

        result.setCode(500);

        result.setMessage(message);

        return result;

    }

}

五、测试用例

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

package com.example.redisnearby;

import com.example.redisnearby.dto.NearbyUserDTO;

import com.example.redisnearby.entity.UserLocation;

import com.example.redisnearby.service.NearbyService;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest

class NearbyServiceTest {

    @Autowired

    private NearbyService nearbyService;

    @Test

    void testNearby() {

        // 模拟添加一些用户位置(北京天安门附近)

        // 天安门坐标:116.397428, 39.90923

        // 用户1:在天安门

        nearbyService.updateLocation(UserLocation.builder()

            .userId("1001")

            .username("张三")

            .avatar("http://example.com/avatar1.jpg")

            .longitude(116.397428)

            .latitude(39.90923)

            .build());

        // 用户2:距离天安门 1公里

        nearbyService.updateLocation(UserLocation.builder()

            .userId("1002")

            .username("李四")

            .avatar("http://example.com/avatar2.jpg")

            .longitude(116.407428)

            .latitude(39.90923)

            .build());

        // 用户3:距离天安门 10公里

        nearbyService.updateLocation(UserLocation.builder()

            .userId("1003")

            .username("王五")

            .avatar("http://example.com/avatar3.jpg")

            .longitude(116.497428)

            .latitude(39.90923)

            .build());

        // 搜索附近5公里的人

        System.out.println("=== 搜索天安门附近5公里的人 ===");

        List<NearbyUserDTO> nearbyUsers = nearbyService.findNearbyUsers(

            116.397428, 39.90923, 5000.0, 10);

        nearbyUsers.forEach(user -> {

            System.out.printf("用户: %s, 距离: %.2f米%n",

                user.getUsername(), user.getDistance());

        });

        // 计算两个用户距离

        Double distance = nearbyService.getDistance("1001", "1002");

        System.out.printf("%n1001和1002之间的距离: %.2f米%n", distance);

    }

}

六、Redis 命令行验证

启动 Redis 后,可以用以下命令验证数据:

1

2

3

4

5

6

7

8

# 查看所有位置成员

ZRANGE user:location 0 -1 WITHSCORES

# 查看某个成员的坐标

GEOPOS user:location 1001 1002

# 手动搜索附近的人

GEORADIUS user:location 116.397428 39.90923 5000 m WITHDIST WITHCOORD ASC

# 查看用户详细信息

HGETALL user:info:1001

七、性能优化建议

优化点 方案
数据分片 按城市或地理网格分片存储,避免单个key数据过大
定期清理 设置 TTL 或定时任务清理不活跃用户信息
缓存用户信息 使用本地缓存(Caffeine)减少 Redis 访问
限流 对搜索接口 做限流,防止恶意刷接口
坐标精度 根据业务需求,适当降低坐标精度(如保留6位小数)

八、项目结构

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

redis-nearby/

├── src/main/java/com/example/redisnearby/

│   ├── config/

│   │   └── RedisConfig.java

│   ├── controller/

│   │   └── NearbyController.java

│   ├── dto/

│   │   └── NearbyUserDTO.java

│   ├── entity/

│   │   └── UserLocation.java

│   ├── service/

│   │   └── NearbyService.java

│   ├── vo/

│   │   └── Result.java

│   └── RedisNearbyApplication.java

├── src/main/resources/

│   └── application.yml

└── pom.xml

九、总结

实现了基于 Redis GEO 的"附近的人"功能,核心优势:

  1. 高性能:Redis 内存操作,毫秒级响应
  2. 简单易用:Spring Data Redis 封装了复杂命令
  3. 功能完善:支持距离计算、范围搜索、排序等
  4. 扩展性强:可结合 GeoHash 实现更复杂的地理需求

版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 :
相关文章
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计