1、业务需求:用户信息存储经纬度,根据某个经纬度查询附近的人,已圆为中心,可根据距离从近到远排序。
2、使用技术:php,redis geo(geoadd,georadius),存储格式为:zset(有序集合)
3、相关文档:http://redisdoc.com/geo/georadius.html
实现:
<?php
/**
* @author
* @since
*/
header("Content-type: text/html; charset=utf-8"); //编码
ini_set('date.timezone', 'Asia/Shanghai'); //定义时间地点
ini_set('memory_limit', '2024M'); //扩展php内存
class statistics
{
protected $redis;
public function __construct()
{
$this->redis = new Redis();
$this->redis->connect('127.0.0.1', 6379);
}
public function index()
{
$total = 500000; //总数
//模拟生成坐标,循环写入
for ($i = 0; $i < $total; $i++) {
//有效的经度介于 -180 度至 180 度之间。
//有效的纬度介于 -85.05112878 度至 85.05112878 度之间。
$num = $this->randomFloat(-85, 85);
$latitude = sprintf("%.6f", $num); //维度
$num = $this->randomFloat(-180, 180);
$longitude = sprintf("%.6f", $num); //经度
$this->redis->rawCommand('geoadd', 'user_info', $longitude, $latitude, 'user_id_' . $i);
}
echo '>>>>>' . date('Y-m-d H:i:s', time()) . '>>>>>';
}
function randomFloat($min = 0, $max = 1)
{
return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}
public function __destruct()
{
$cx = '39.90'; //纬度
$cy = '116.40'; //经度
//获取本经纬度坐标100km内容的信息并根据距离从近到远排序显示5条
$rediss = $this->redis->rawCommand('georadius', 'user_info', $cy, $cx, '100', 'km', 'WITHCOORD', 'WITHDIST', 'ASC', 'COUNT', 5);
echo json_encode($rediss);
}
}
$tg = new statistics();
$tg->index();
查看数据,redis存储方式:
打印结果: