Obtain regional information services for rental projects


technological process



# Request: 
method: GET
url: api/v1.0/areas
# data:
no input data

# Response:
#Return success
    "errno": 0,
    "errmsg": "ok",
    "data": [
        {"aid": 1, "aname": "Dongcheng District"},
        {"aid": 2, "aname": "Xicheng District"},
#Return failed
	"Errno": "400X", // status code
    "Errmsg": "status error messages"

Create command

$ micro new --type "srv" ihome/GetArea

Modify nameexample.protobygetarea.proto, the name of the upper level folder is also determined byexampleChange togetarea

[email protected]:~/go/src/ihome/GetArea/proto$ tree
└── getarea
    └── getarea.proto

1 directory, 1 files

Redis installation

For details on the installation and use of redis, please see this article: introduction and installation of redis

Install redis


$ wget http://download.redis.io/releases/redis-6.0.5.tar.gz

Or go to the website to download the specified version: http://download.redis.io/releases/


$ tar xzf redis-6.0.5.tar.gz

get into

$ cd redis-6.0.5


$ make


$ sudo make install


$ redis-cli
Could not connect to Redis at Connection refused
not connected>


Start redis

The redis installation packageredis.confCopy the file to the conf folder of iHome service in the project

Then, modifyredis.conffile

#About 69 rows
Bind current host IP
#Change line 136 to yes, indicating that the daemon is started
daemonize yes

Create a startup file in the iHome service

$ sudo vim server.sh

File content

redis-server ./conf/redis.conf

Give the file startup permission

$ chmod 777 server.sh

Install redis API driver of go language

$ go get -v -u github.com/gomodule/redigo/redis
$ go get -v -u github.com/garyburd/redigo

Install the cache module of beego

$ go get -v -u github.com/astaxie/beego/cache

Write ptoro file

syntax = "proto3";

package go.micro.srv.GetArea;

service Example {
  rpc GetArea(Request) returns (Response) {}

message Request {


message Response {
  //Return error code
  string ErrNo = 1;
  //Return error message
  string ErrMsg = 2;
  //Return data type
  message Area {
    int32 Aid = 1;
    string Aname = 2;
  //Array returned with custom type
  repeated Area Data = 3;
$ cd /home/lpgit/go/src/ihome/GetArea
$ protoc --proto_path=. --go_out=. --micro_out=. proto/getarea/getarea.proto

Web side

Modify main.go file: add route

//Get regional information
rou.GET("/api/v1.0/areas", handler.GetArea)


package handler

import (
	getarea "ihome/GetArea/proto/getarea"

//Get regional information
func GetArea(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	//Create a new grpc return handle
	server := grpc.NewService()
	//Service initialization

	//Create a service that gets the region and returns a handle
	exampleClient := getarea.NewExampleService("go.micro.srv.GetArea", server.Client())
	//Call the function and return data
	rsp, err := exampleClient.GetArea(context.TODO(), &getarea.Request{})
	if err != nil {
	//Create slice of return type
	var areas []models.Area
	//Loop reading the data returned by the service
	for _, value := range rsp.Data {
		areas = append(areas, models.Area{Id: int(value.Aid), Name: value.Aname})
	//Create return data map
	response := map[string]interface{}{
		"errno":  rsp.ErrNo,
		"errmsg": rsp.ErrMsg,
		"data":   areas,
	w.Header().Set("Content-Type", "application/json")

	//Send the returned data map to the front end
	if err := json.NewEncoder(w).Encode(response); err != nil {
		http.Error(w, err.Error(), 503)

Server side

modifymain.goContent,After that, modify it every time as follows

package main

import (
    //Modify here
	getarea "ihome/GetArea/proto/getarea"

func main() {
	// New Service
    //Modify here:micro 改为 grpc
	service := grpc.NewService(

	// Initialise service

	// Register Handler
    //Modify here example 改为 getarea
    //Change handler.example to handler.server
	getarea.RegisterExampleHandler(service.Server(), new(handler.Server))

	// Run service
	if err := service.Run(); err != nil {


package handler

import (

	_ "github.com/astaxie/beego/cache/redis"
	_ "github.com/garyburd/redigo/redis"
	_ "github.com/gomodule/redigo/redis"
	getarea "ihome/GetArea/proto/getarea"

type Server struct{}

func (e *Server) GetArea(ctx context.Context, req *getarea.Request, rsp *getarea.Response) error {
	//Initialization error code
	rsp.ErrNo = utils.RECODE_OK
	rsp.ErrMsg = utils.RecodeText(rsp.ErrNo)

	//1. Get data from cache
	//Preparing to connect to redis information
	redisConf := map[string]string{
		"key":   utils.G_server_name,
		"conn":  utils.G_redis_addr + ":" + utils.G_redis_port,
		"dbNum": utils.G_redis_dbnum,

	//Convert map to JSON
	redisConfJson, _ := json.Marshal(redisConf)
	//Create redis handle
	bm, err := cache.NewCache("redis", string(redisConfJson))
	if err != nil {
		rsp.ErrNo = utils.RECODE_DBERR
		rsp.ErrMsg = utils.RecodeText(rsp.ErrNo)
		return nil
	//Get data
	areaInfo := bm.Get("areaInfo")
	if areaInfo != nil {
		//Data in cache
		var areas []map[string]interface{}
		//Decode the acquired data
		json.Unmarshal(areaInfo.([]byte), &areas)

		for _, value := range areas {
			rsp.Data = append(rsp.Data, &getarea.Response_Area{Aid: int32(value["aid"].(float64)), Aname: value["aname"].(string)})
		return nil

	//2. There is no data in the cache. Look up the data from mysql
	o := orm.NewOrm()
	var areas []models.Area
	num, err := o.QueryTable("Area").All(&areas)
	if err != nil {
		rsp.ErrNo = utils.RECODE_DBERR
		rsp.ErrMsg = utils.RecodeText(rsp.ErrNo)
		return nil
	if num <= 0 {
		rsp.ErrNo = utils.RECODE_NODATA
		rsp.ErrMsg = utils.RecodeText(rsp.ErrNo)
		return nil

	//3. Save the found data to the cache
	//Convert the obtained data into JSON format
	areasJson, _ := json.Marshal(areas)
	err = bm.Put("areaInfo", areasJson, 3600*time.Second)
	if err != nil {
		rsp.ErrNo = utils.RECODE_DBERR
		rsp.ErrMsg = utils.RecodeText(rsp.ErrNo)
		return nil

	//4. Send the found data to the front end in proto format
	for _, value := range areas {
		rsp.Data = append(rsp.Data, &getarea.Response_Area{Aid: int32(value.Id), Aname: value.Name})
	return nil

Li peiguan blog

Welcome to my personal website:

Li peiguan blog: lpgit.com