类似nginx的反向代理,将8081端口请求代理到后端服务8001 8002 和 8003
轮训方式,无负载均衡服务发现等
package main
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"sync/atomic"
)
var backendServiceCount = 3
/**
后端服务组
*/
var backendServiceList = make([]*httputil.ReverseProxy, backendServiceCount)
var index int64 = 0
func init() {
for i := 0; i < backendServiceCount; i++ {
url, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", (8001 + i)))
log.Println("初始化后端服务", url)
proxy := httputil.NewSingleHostReverseProxy(url)
backendServiceList[i] = proxy
}
}
/**
反向代理给后端服务
*/
func rproxy(w http.ResponseWriter, r *http.Request) {
//轮训方式选择一个后端服务
i := atomic.AddInt64(&index, 1)
proxy := backendServiceList[i%int64(backendServiceCount)]
proxy.ServeHTTP(w, r)
}
/**
反向代理
将8081端口请求代理到后端服务8001 8002 和 8003
*/
func main() {
http.HandleFunc("/", rproxy)
log.Fatal(http.ListenAndServe(":8000", nil))
}
网友评论