周梦康 发表于 2015-06-06 3372 次浏览 标签 : Javageo

实际应用场景.用户发 feed 的时候带上该用户的经纬度,这样在入库之后,会在后端里再通过 http 去请求我们的 geo 服务的 api. 

服务器端代码:

var express = require('express');
var app     = express();

var redis 	= require('redis'),
	redis_client  = redis.createClient(6879 , '127.0.0.1' ,{connect_timeout:1}); //最后参数是超时时间

redis_client.on('error' , function(error ,res) {
	res.send(error);
});

app.get('/api_lbs/hujia/geo_set' , function(req , res){

	//定义返回的json
	var return_data ;

	//得到资源id ,用户id,经纬度信息
	var res_id 		= req.query.fid;		// feed id
	var uid			= req.query.uid;		// uid
	var res_type	= req.query.type;		// feed/user
	var latitude	= req.query.latitude;	// 纬度
	var longitude	= req.query.longitude;	// 经度
	var sendtime	= req.query.ts;		    // 发帖的时间
	var keyPrefix	= req.query.keyPrefix;	// key 的前缀

	if(!res_id || !res_type || !latitude || !longitude) {
		res.contentType("json");
		res.send(JSON.stringify({ status : "-1",msg : "参数不全"}));
		res.end();
	}
	
	var key = keyPrefix + ':' + res_type;
	var info = res_id + '_' + uid;
	var rl = redis_client.send_command('geoadd',[key,latitude,longitude,info]);
	
	var expire = 3600*24*30;
	redis_client.expire(key,expire);

	if(!req.query.posiname){
		//存储地标名和经纬度关系
		var posiname = req.query.posiname;	// 地标名
		var geo = latitude + '_' + longitude; 
		redis_client.set(posiname,geo);
	}
	
	res.contentType("json");
	res.send(JSON.stringify({ status : '1',msg:'添加成功'}));
	res.end();
});

app.get('/api_lbs/hujia/geo_get' , function(req , res) {

	//得到资源id,经纬度信息
	var res_type 	= req.query.type;
	var latitude	= req.query.latitude;
	var longitude	= req.query.longitude;
	var radius		= req.query.radius;//半径
	var keyPrefix   = req.query.keyPrefix;
	
	if(!res_type || !latitude || !longitude) {
		res.send(JSON.stringify({ status : '-1',msg : '参数不全'}));
		res.end();
	}

	if(!radius) {
		radius = parseInt(2);
	} else {
		radius = parseInt(radius);
	}

	var key = keyPrefix + ':' + res_type;
	var args  = [key,latitude,longitude,radius,'km','withdistance','desc'];

	redis_client.send_command('georadius',args,function(err,response){
		if(err){
			res.contentType("json");
			res.send(JSON.stringify({ status : '-2',msg : '查询出错'}));
		}else{
			res.send(JSON.stringify({ status : '1',data:response}));   	
		}
		res.end();
	});
});
app.listen(8085);//监听端口

客户端通过http请求后端 geo 服务器.

存:http://192.168.50.160:8085/api_lbs/hujia/geo_set?fid=10&uid=24&keyPrefix=hujia&type=feed&ts=1433585297&latitude=39.909987&longitude=116.461442

取:http://192.168.50.160:8085/api_lbs/hujia/geo_get?fid=10&uid=24&type=feed&ts=1433584221&latitude=39.919987&longitude=116.461442&keyPrefix=hujia

客户端(java)向后端(node)请求:

package me.topit.site.api;

import me.topit.site.Constants;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by zhoumengkang on 5/6/15.
 */
public class GeoApi extends BaseApi {

    /**
     * 把用户发的 feed 添加到 geo 中
     * @param fid
     * @param uid
     * @param type  保存的类型,现在默认都是 feed
     * @param geo   eg. 39.909987,116.461442
     */
    public static void add(int fid,int uid,String type,String geo){
        BufferedReader in = null;
        String geoArray[] = geo.split(",");
        if (geoArray.length < 1) return;

        String params = "";
        params += "fid=" + fid;
        params += "&uid=" + uid;
        params += "&keyPrefix=hujia";
        params += "&type=" + type;
        params += "&ts=" + (int) (System.currentTimeMillis()/1000);
        params += "&latitude=" + geoArray[0];
        params += "&longitude=" + geoArray[1];

        try {
            String urlNameString = Constants.GeoSetApi + "?" + params;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            connection.setConnectTimeout(1500);
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "keep-Alive"); // 这个地方是 close 还是 keep-Alive
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } catch (Exception e) {
            loggerInit(GeoService.class).error("geo 写入失败 {}",e.toString(),e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                loggerInit(GeoService.class).error("geo 连接关闭失败 {}", e2.toString(), e2);
            }
        }
    }

    public static String get(String type,String geo){
        String result = "";
        BufferedReader in = null;
        String geoArray[] = geo.split(",");
        if (geoArray.length < 1) return null;

        String params = "";
        params += "type=" + type;
        params += "&radius=3";
        params += "&keyPrefix=hujia";
        params += "&ts=" + (int) (System.currentTimeMillis()/1000);
        params += "&latitude=" + geoArray[0];
        params += "&longitude=" + geoArray[1];

        try {
            String urlNameString = Constants.GeoGetApi + "?" + params;
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setConnectTimeout(1500);
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            loggerInit(GeoService.class).error("geo 获取失败 {}",e.toString(),e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                loggerInit(GeoService.class).error("geo 连接关闭失败 {}", e2.toString(), e2);
            }
        }
        return result;
    }
}

👇 下面是我的公众号,高质量的博文我会第一时间同步到公众号,给个关注吧!

评论列表