grace 模块

What is Hot Upgrade?

What is hot upgrade? Students who know nginx know that nginx supports hot upgrade. It can use the old process to serve the previous link and the new process to serve the new link, that is, to complete the system upgrade and operating parameter modification without stopping the service. Then hot upgrade and hot compilation are different concepts. Hot compilation is to recompile by monitoring file changes, and then restart the process, For example bee run is such a tool

Is hot upgrade necessary?

Many people think that it is necessary for HTTP applications to support hot upgrades? Then I can say very responsibly that it is very necessary. Uninterrupted service is always the goal we pursue. Although many people say that the server may be broken, etc., this belongs to the high-availability design category. Don’t confuse it. This is Predictable problems, so we need to avoid user unavailability caused by such an upgrade. Are you still troubled by the early morning upgrade for the previous upgrade? So hurry up and embrace the hot upgrade now.

grace module

The grace module is a newly added module of beego that independently supports hot restart. The main idea comes from: http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/

How to use hot upgrade

 import(
   "log"
	"net/http"
	"os"
    "strconv"

   "github.com/beego/beego/v2/server/web/grace"
 )

  func handler(w http.ResponseWriter, r *http.Request) {
	  w.Write([]byte("WORLD!"))
      w.Write([]byte("ospid:" + strconv.Itoa(os.Getpid())))
  }

  func main() {
      mux := http.NewServeMux()
      mux.HandleFunc("/hello", handler)

      err := grace.ListenAndServe("localhost:8080", mux)
      if err != nil {
		   log.Println(err)
	    }
      log.Println("Server on 8080 stopped")
	     os.Exit(0)
    }

open two terminals

A terminal input: ps -ef|grep appname

A terminal input request: curl "http://127.0.0.1:8080/hello"

hot upgrade

kill -HUP process ID

Open a terminal and enter the request: curl "http://127.0.0.1:8080/hello?sleep=0"