search
HomeDatabaseRedisUse Redis to complete the WeChat shake function

Redis provides the geographical location information (GEO) function, with which you can complete functions such as nearby people and shake. First, let’s introduce the relevant APIs of GEO.

GEO API

Add address location information

# #geoadd key longitude latitude member [longitude latitude member ...]

  • longitude : longitude

  • latitude : latitude

  • member: member

This command can add one or more members at a time

There are some users, all in Hefei, now add Their geographical coordinates are stored in Redis.

  • Little A is watching TV at home. The coordinates of his home are: 117.230279,31.81676

  • Little B is working overtime at the company, and the coordinates of the company are: :117.229704,31.824676

  • Little C is on a business trip, and the address coordinates of his business trip are: 117.300419,31.696095

  • Little D is taking care of his baby at home. The address coordinates of his home are: 117.192909,31.732465

  • Little E is still in school, and the address coordinates of his school are: 117.189604,31.838297

  • 127.0.0.1:6379> geoadd location 117.230279 31.81676 a 117.229704 31.824676 b
    (integer) 2
    127.0.0.1:6379> geoadd location 117.300419 31.696095 c
    (integer) 1
    127.0.0.1:6379> geoadd location 117.192909 31.732465 d
    (integer) 1
    127.0.0.1:6379> geoadd location 117.189604 31.838297 e
    (integer) 1

Get the distance between two locations

##geodist key member1 member2 [unit]

unit has four units

    'm' => meters
  • 'km' => kilometers
  • 'mi ' => Mile
  • 'ft' => Foot
  • We mainly use meters and kilometers.

Now let’s take a look at the distance between Little A and Little B

127.0.0.1:6379> GEODIST location a b km
"0.8821"

You can see that there is 0.88 kilometers between Little A and Little B

Let’s take a look again The distance between Little C and Little E

127.0.0.1:6379> GEODIST location c e km
"18.9728"

The difference between them is nearly 19 kilometers.

Get address location information

geopos key member [member ...]

come Look at the longitude and latitude information of Xiao D’s address

127.0.0.1:6379> geopos location d
1) 1) "117.19290822744369507"
   2) "31.73246441933707018"

Get the geographical information location collection within the specified location range

georadius key longitude latitude radiusm km|ft|mi [withcoord] [withdist] [withhash] [COUNT count] [asc|desc] [store key] [storedist key] georadiusbymember key member radiusm km|ft|mi [withcoord] [withdist] [ withhash] [COUNT count] [asc|desc] [store key] [storedist key]

These two commands are slightly more complicated than the others. Let's take a look at these two commands together.

The functions of these two commands are basically similar. The main difference is that the first command gives the specific longitude and latitude, while the second command only gives the member name. For example, I want to know the distance between members and Dashu Mountain in Hefei. Because the longitude and latitude information of Dashu Mountain has not been stored in redis, we need to use the first command to input the longitude and latitude of Dashu Mountain. For another example, to determine the distance of other members from the coordinates of Little A, you can use the second command and directly enter member Little A.

radiusm and the following units are required information, specifying the radius distance to search within.

The coordinates of Hefei Dashu Mountain are 117.175571,31.846746

# 查看离大蜀山10km的成员有哪些
127.0.0.1:6379> GEORADIUS location 117.175571 31.846746 10 km
1) "e"
2) "a"
3) "b"

You can see that small e, small a and small b are relatively close to Dashu Mountain, within 10km.

WITHCOORD: Return the longitude and latitude of the location element as well

127.0.0.1:6379> GEORADIUS location 117.175571 31.846746 10 km withcoord
1) 1) "e"
   2) 1) "117.18960374593734741"
      2) "31.83829663190295634"
2) 1) "a"
   2) 1) "117.23027676343917847"
      2) "31.81675910621205361"
3) 1) "b"
   2) 1) "117.22970277070999146"
      2) "31.8246750403926697"
You can see that in addition to the members, the member’s location information page is also included Given

withdist: the returned result contains the distance from the central node position

127.0.0.1:6379> GEORADIUS location 117.175571 31.846746 10 km withcoord withdist
1) 1) "e"
   2) "1.6252"
   3) 1) "117.18960374593734741"
      2) "31.83829663190295634"
2) 1) "a"
   2) "6.1522"
   3) 1) "117.23027676343917847"
      2) "31.81675910621205361"
3) 1) "b"
   2) "5.6737"
   3) 1) "117.22970277070999146"
      2) "31.8246750403926697"
You can see that small E is 1.62 kilometers away from Dashu Mountain, and small A is 1.62 kilometers away from Dashu Mountain. Shushan is 6.15 kilometers away, and Little B is 5.67 kilometers away from Shushan.

withhash: This command can be ignored and basically not used.

COUNT count: Specify the number of returned results.

asc|desc: The returned results are in ascending or descending order according to the distance from the center node.

storedist key: Save the distance of the returned result from the center node to the specified key.

# 获取离大蜀山100km内范围的成员,按距离的升序,只需给出最近的4个成员即可
127.0.0.1:6379> GEORADIUS location 117.175571 31.846746 100 km withdist count 4 asc
1) 1) "e"
   2) "1.6252"
2) 1) "b"
   2) "5.6737"
3) 1) "a"
   2) "6.1522"
4) 1) "d"
   2) "12.8164"

Practical combatAfter introducing the above knowledge, you can use php combined with redis to complete the shake to find people nearby function. First, save the location information of the members.

伪代码如下:

function addLocation ($key,$member, $lng, $lat)
{
    $redis->geoadd($key, $lng, $lat, $member);
}

然后,获取附近的人的信息

function near (
    $key, 
    $member, 
    $radius, 
    $unit = 'km', 
    $count = 0,  
    $withDist = false, 
    $withcoord = false, 
    $orderby = 'ASC'
)
{
    $redis = new Redis();
    $redis->connect('localhost', 6379);
    $options = [$orderby];
    if ($count > 0) {
        $options['count'] = $count;
    }
    if ($withDist) {
        $options[] = 'WITHDIST';
    }
    if ($withcoord) {
        $options[] = 'WITHCOORD';
    }
    $result = $redis->geoRadiusByMember($key, $member, $radius, $unit, $options);
    return $result;
}

使用redis可以大大方便开发人员,丰富的API可以完成各种各样的需求,Redis的使用已经成为程序员必备的技能了。

The above is the detailed content of Use Redis to complete the WeChat shake function. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Redis: Exploring Its Features and FunctionalityRedis: Exploring Its Features and FunctionalityApr 19, 2025 am 12:04 AM

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

Is Redis a SQL or NoSQL Database? The Answer ExplainedIs Redis a SQL or NoSQL Database? The Answer ExplainedApr 18, 2025 am 12:11 AM

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis: Improving Application Performance and ScalabilityRedis: Improving Application Performance and ScalabilityApr 17, 2025 am 12:16 AM

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis: Exploring Its Data Model and StructureRedis: Exploring Its Data Model and StructureApr 16, 2025 am 12:09 AM

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis: Classifying Its Database ApproachRedis: Classifying Its Database ApproachApr 15, 2025 am 12:06 AM

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Why Use Redis? Benefits and AdvantagesWhy Use Redis? Benefits and AdvantagesApr 14, 2025 am 12:07 AM

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Understanding NoSQL: Key Features of RedisUnderstanding NoSQL: Key Features of RedisApr 13, 2025 am 12:17 AM

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

Redis: Identifying Its Primary FunctionRedis: Identifying Its Primary FunctionApr 12, 2025 am 12:01 AM

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools