如何在 Java 中利用 redis 实现 LBS 服务

前言

LBS(基于位置的服务) 服务是现在移动互联网中比较常用的功能。例如外卖服务中常用的我附近的店铺的功能,通常是以用户当前的位置坐标为基础,查询一定距离范围类的店铺,按照距离远近进行倒序排序。

自从 redis 4 版本发布后, lbs 相关命令正式内置在 redis 的发行版中。要实现上述的功能,主要用到 redis geo 相关的两个命令

GEOADD 和 GEORADIOUS

命令描述

GEOADD

GEOADD key longitude latitude member [longitude latitude member ...]

这个命令将指定的地理空间位置(纬度、经度、名称)添加到指定的 key 中。

有效的经度从-180度到180度。

有效的纬度从-85.05112878度到85.05112878度。

当坐标位置超出上述指定范围时,该命令将会返回一个错误。

该命令可以一次添加多个地理位置点

GEORADIOUS

GEORADIUS key longitude latitude radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count]

这个命令以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素。
范围可以使用以下其中一个单位:

  • m 表示单位为米。
  • km 表示单位为千米。
  • mi 表示单位为英里。
  • ft 表示单位为英尺。

在给定以下可选项时, 命令会返回额外的信息:

  • WITHDIST: 在返回位置元素的同时, 将位置元素与中心之间的距离也一并返回。 距离的单位和用户给定的范围单位保持一致。
  • WITHCOORD: 将位置元素的经度和维度也一并返回。
  • WITHHASH: 以 52 位有符号整数的形式, 返回位置元素经过原始 geohash 编码的有序集合分值。 这个选项主要用于底层应用或者调试, 实际中的作用并不大。
  • ASC: 根据中心的位置, 按照从近到远的方式返回位置元素。
  • DESC: 根据中心的位置, 按照从远到近的方式返回位置元素。
  • 在默认情况下, GEORADIUS 命令会返回所有匹配的位置元素。 虽然用户可以使用 COUNT <count> 选项去获取前 N 个匹配元素

接口定义

package com.x9710.common.redis;
import com.x9710.common.redis.domain.GeoCoordinate;
import com.x9710.common.redis.domain.Postion;
import java.util.List;
public interface LBSService {
/**
* 存储一个位置
*
* @param postion 增加的位置对象
* @throws Exception
*/
boolean addPostion(Postion postion);
/**
* 查询以指定的坐标为中心,指定的距离为半径的范围类的所有位置点
*
* @param center 中心点位置
* @param distinct 最远距离,单位米
* @param asc 是否倒序排序
* @return 有效的位置
*/
List<Postion> radious(String type, GeoCoordinate center, Long distinct, Boolean asc);
}

实现的接口

package com.x9710.common.redis.impl;
import com.x9710.common.redis.LBSService;
import com.x9710.common.redis.RedisConnection;
import com.x9710.common.redis.domain.GeoCoordinate;
import com.x9710.common.redis.domain.Postion;
import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.geo.GeoRadiusParam;
import java.util.ArrayList;
import java.util.List;
public class LBSServiceRedisImpl implements LBSService {
private RedisConnection redisConnection;
private Integer dbIndex;

public void setRedisConnection(RedisConnection redisConnection) {
this.redisConnection = redisConnection;
}
public void setDbIndex(Integer dbIndex) {
this.dbIndex = dbIndex;
}
public boolean addPostion(Postion postion) {
Jedis jedis = redisConnection.getJedis();
try {
return (1L == jedis.geoadd(postion.getType(),
postion.getCoordinate().getLongitude(),
postion.getCoordinate().getLatitude(),
postion.getId()));
} finally {
if (jedis != null) {
jedis.close();
}
}
}
public List<Postion> radious(String type, GeoCoordinate center, Long distinct, Boolean asc) {
List<Postion> postions = new ArrayList<Postion>();
Jedis jedis = redisConnection.getJedis();
try {
GeoRadiusParam geoRadiusParam = GeoRadiusParam.geoRadiusParam().withCoord().withDist();
if (asc) {
geoRadiusParam.sortAscending();
} else {
geoRadiusParam.sortDescending();
}
List<GeoRadiusResponse> responses = jedis.georadius(type,
center.getLongitude(),
center.getLatitude(),
distinct.doubleValue(),
GeoUnit.M,
geoRadiusParam);
if (responses != null) {
for (GeoRadiusResponse response : responses) {
Postion postion = new Postion(response.getMemberByString(),
type,
response.getCoordinate().getLongitude(),
response.getCoordinate().getLatitude());
postion.setDistinct(response.getDistance());
postions.add(postion);
}
}
} finally {
if (jedis != null) {
jedis.close();
}
}
return postions;
}
}

测试用例

package com.x9710.common.redis.test;
import com.x9710.common.redis.RedisConnection;
import com.x9710.common.redis.domain.GeoCoordinate;
import com.x9710.common.redis.domain.Postion;
import com.x9710.common.redis.impl.CacheServiceRedisImpl;
import com.x9710.common.redis.impl.LBSServiceRedisImpl;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
/**
* LBS服务测试类
*
* @author 杨高超
* @since 2017-12-28
*/
public class RedisLBSTest {
private CacheServiceRedisImpl cacheService;
private LBSServiceRedisImpl lbsServiceRedis;
private String type = "SHOP";
private GeoCoordinate center;
@Before
public void before() {
RedisConnection redisConnection = RedisConnectionUtil.create();
lbsServiceRedis = new LBSServiceRedisImpl();
lbsServiceRedis.setDbIndex(15);
lbsServiceRedis.setRedisConnection(redisConnection);
Postion postion = new Postion("2017122801", type, 91.118970, 29.654210);
lbsServiceRedis.addPostion(postion);
postion = new Postion("2017122802", type, 116.373472, 39.972528);
lbsServiceRedis.addPostion(postion);
postion = new Postion("2017122803", type, 116.344820, 39.948420);
lbsServiceRedis.addPostion(postion);
postion = new Postion("2017122804", type, 116.637920, 39.905460);
lbsServiceRedis.addPostion(postion);
postion = new Postion("2017122805", type, 118.514590, 37.448150);
lbsServiceRedis.addPostion(postion);
postion = new Postion("2017122806", type, 116.374766, 40.109508);
lbsServiceRedis.addPostion(postion);
center = new GeoCoordinate();
center.setLongitude(116.373472);
center.setLatitude(39.972528);
}
@Test
public void test10KMRadious() {
List<Postion> postions = lbsServiceRedis.radious(type, center, 1000 * 10L, true);
Assert.assertTrue(postions.size() == 2 && exist(postions, "2017122802") && exist(postions, "2017122803"));
}
@Test
public void test50KMRadious() {
List<Postion> postions = lbsServiceRedis.radious(type, center, 1000 * 50L, true);
Assert.assertTrue(postions.size() == 4
&& exist(postions, "2017122802")
&& exist(postions, "2017122803")
&& exist(postions, "2017122806")
&& exist(postions, "2017122804"));
}
private boolean exist(List<Postion> postions, String key) {
if (postions != null) {
for (Postion postion : postions) {
if (postion.getId().equals(key)) {
return true;
}
}
}
return false;
}
@Before
public void after() {
RedisConnection redisConnection = RedisConnectionUtil.create();
cacheService = new CacheServiceRedisImpl();
cacheService.setDbIndex(15);
cacheService.setRedisConnection(redisConnection);
cacheService.delObject(type);
}
}

测试结果

LBS 服务测试结果

后记

这样,我们通过 redis 就能简单实现一个我附近的小店的功能的 LBS服务。

代码同步发布在 GitHub 仓库

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Java连接redis及基本操作示例

    本文实例讲述了Java连接redis及基本操作.分享给大家供大家参考,具体如下: 点击此处:本站下载安装. 解压安装 启动redis:使用cd命令切换目录到 D:\redis运行redis-server.exe redis.windows.conf 默认端口为6379 访问:切换到redis目录下运行 redis-cli.exe -h 127.0.0.1 -p 6379. pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0&

  • Java使用Redisson分布式锁实现原理

    1. 基本用法 <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.8.2</version> </dependency> Config config = new Config(); config.useClusterServers() .setScanInterval(2000) /

  • 在Java中使用redisTemplate操作缓存的方法示例

    背景 在最近的项目中,有一个需求是对一个很大的数据库进行查询,数据量大概在几千万条.但同时对查询速度的要求也比较高. 这个数据库之前在没有使用Presto的情况下,使用的是Hive,使用Hive进行一个简单的查询,速度可能在几分钟.当然几分钟也并不完全是跑SQL的时间,这里面包含发请求,查询数据并且返回数据的时间的总和.但是即使这样,这样的速度明显不能满足交互式的查询需求. 我们的下一个解决方案就是Presto,在使用了Presto之后,查询速度降到了秒级.但是对于一个前端查询界面的交互式查询来

  • 详解Java在redis中进行对象的缓存

    Java在redis中进行对象的缓存一般有两种方法,这里介绍序列化的方法,个人感觉比较方便,不需要转来转去. 一.首先,在存储的对象上实现序列化的接口 package com.cy.example.entity.system; import java.util.List; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableName; im

  • 详解在Java程序中运用Redis缓存对象的方法

    这段时间一直有人问如何在Redis中缓存Java中的List 集合数据,其实很简单,常用的方式有两种: 1. 利用序列化,把对象序列化成二进制格式,Redis 提供了 相关API方法存储二进制,取数据时再反序列化回来,转换成对象. 2. 利用 Json与java对象之间可以相互转换的方式进行存值和取值. 正面针对这两种方法,特意写了一个工具类,来实现数据的存取功能. 1. 首页在Spring框架中配置 JedisPool 连接池对象,此对象可以创建 Redis的连接 Jedis对象.当然,必须导

  • 如何在 Java 中利用 redis 实现 LBS 服务

    前言 LBS(基于位置的服务) 服务是现在移动互联网中比较常用的功能.例如外卖服务中常用的我附近的店铺的功能,通常是以用户当前的位置坐标为基础,查询一定距离范围类的店铺,按照距离远近进行倒序排序. 自从 redis 4 版本发布后, lbs 相关命令正式内置在 redis 的发行版中.要实现上述的功能,主要用到 redis geo 相关的两个命令 GEOADD 和 GEORADIOUS 命令描述 GEOADD GEOADD key longitude latitude member [longi

  • 如何在Java中调用python文件执行详解

    目录 一.Java内置Jpython库(不推荐) 1.1 下载与使用 1.2 缺陷 二.使用Runtime.getRuntime()执行脚本⽂件 2.1 使用 2.2 缺陷 三.利用cmd调用python文件 3.1 使用 3.2 优化 总结 一.Java内置Jpython库(不推荐) 1.1 下载与使用 可以在官网下载jar包,官网:http://ftp.cuhk.edu.hk/pub/packages/apache.org/ 或者使用maven进行jar包下载 <dependency> &

  • java中利用反射调用另一类的private方法的简单实例

    我们知道,Java应用程序不能访问持久化类的private方法,但Hibernate没有这个限制,它能够访问各种级别的方法,如private, default, protected, public. Hibernate是如何实现该功能的呢?答案是利用JAVA的反射机制,如下: import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class ReflectDemo {

  • Java 中利用泛型和反射机制抽象DAO的实例

    Java 中利用泛型和反射机制抽象DAO的实例 一般的DAO都有CRUD操作,在每个实体DAO接口中重复定义这些方法,不如提供一个通用的DAO接口,具体的实体DAO可以扩展这个通用DAO以提供特殊的操作,从而将DAO抽象到另一层次,令代码质量有很好的提升 1.通用接口 import java.io.Serializable; import java.util.List; public interface BaseDao<T> { T get(Serializable id); List<

  • Java中利用POI优雅的导出Excel文件详解

    前言 故事是这样开始的: 公司给排了几天的工期,让完成 2 个功能模块的开发.其中有一个场景是这样的,从 Excel 导入数据,要求数据不能重复.用户可以下载导入失败的 Excel 文件. 这样就有 2 种实现 将失败数据存储数据库,需要下载时生成 Excel 下载即可 将失败数据生成 Excel 文件存储文件服务器,然后返回下载链接. 老大要求按方案二进行.好吧,导出 Excel 是再常见不过的功能了,然而总是觉得以前写的不够优雅,所以决定进行简单的封装,以适应简单场景的 Excel 导出.

  • 如何在JAVA中使用Synchronized

    <编程思想之多线程与多进程(1)--以操作系统的角度述说线程与进程>一文详细讲述了线程.进程的关系及在操作系统中的表现,这是多线程学习必须了解的基础.本文将接着讲一下Java线程同步中的一个重要的概念synchronized. 在Java中,synchronized关键字是用来控制线程同步的,就是在多线程的环境下,控制synchronized代码段不被多个线程同时执行. synchronized是Java中的关键字,是一种同步锁.它修饰的对象有以下几种: 1. 修饰一个代码块,被修饰的代码块称

  • 如何在java中使用SFTP协议安全的传输文件

    本文介绍在Java中如何使用基于SSH的文件传输协议(SFTP)将文件从本地上传到远程服务器,或者将文件在两个服务器之间安全的传输.我们先来了解一下这几个协议 SSH 是较可靠,专为远程登录会话和其他网络服务提供安全性的协议.比如:我们购买的云服务器登陆的时候使用的协议都是ssh. ftp协议通常是用来在两个服务器之间传输文件的,但是它本质上是不安全的. 那么SFTP是什么?SFTP可以理解为SSH + FTP,也就是安全的网络文件传输协议. 一般来说,SFTP和FTP服务都是使用相应的客户端软

  • java中利用栈实现字符串回文算法

    问题 给定一个由多个a和b组成的字符串数组,字符串中有一个特殊的字符X,位于字符串的正中间,例如(aaaabbbbXabaabbbb),如何判定该字符串是否回文 简单算法 定义两个下标分别指向字符串的头和尾,每次比较两个下标位置的值是否相等,如果不相等,那么输入的 字符串不是回文,如果相等,左边的下表加1,右边的下表减1,重复上述步骤直至两个下标都指向字符串的正中间或者确定字符串不是回文 /** * 判断字符串是否是回文 */ public int isPalindrome(String inp

  • Java中利用Alibaba开源技术EasyExcel来操作Excel表的示例代码

    一.读Excel 1.Excel表格示例 2.对象示例 @Data public class DemoData { private String string; private Date date; private Double doubleData; } 3.监听器(重点部分) // 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去 public class DemoDataListener e

  • 如何在CocosCreator中利用常驻节点做图层管理

    CocosCreator版本:2.3.4 一般游戏都有图层管理,比如 sceneLayer 场景层 panelLayer 弹框层 tipLayer   提示框层 cocos里的场景不是持久化的,每次切换都会自动destroy,如果在场景上放这些图层,那么每个scene都要放一遍?然后再获取,这样很麻烦. 加载场景使用的是cc.director.loadScene,scene的容器node貌似是director上的一个nodeActivator 现在如果不考虑scene的容器或者cocos的顶层容

随机推荐