Golang Microservices Example
A Microservices Architecture consists of a collection of small, autonomous services. Each service is self-contained and should implement a single business capability.
Below is an example of designing and implementing Microservices using:
| Terms | Description |
|---|---|
| 3rd App Service | Outternal services that want to use/integrate with Movie service. |
| API Gateway | The single entry point for all clients. The API gateway proxied/routed requests to the appropriate service. |
| IAM Service | Service that authenticates user and grants authorizations (permissions). |
| Resource Service | Service that hosts protected resources and validates access token during resource access. |
Install Golang
Install MongoDB
Start MongoDB
$ mongod --dbpath="[your_database_path]"$ go get -u github.com/swaggo/swag/cmd/swag github.com/swaggo/gin-swagger github.com/swaggo/gin-swagger/swaggerFiles github.com/alecthomas/template github.com/gin-gonic/gin github.com/sirupsen/logrus gopkg.in/mgo.v2/bson github.com/natefinch/lumberjackGuideline: https://github.com/swaggo/swag
$ git clone https://github.com/raycad/go-microservices.git$ cd [go-microservices]/src/[app_directory]$ swag initNOTE: You can change host and basePath of the service by editting the file ./docs/docs.go
Update values of file ./config/config.json
{
"port": ":8808",
"enableGinConsoleLog": true,
"enableGinFileLog": false,
"logFilename": "logs/server.log",
"logMaxSize": 10,
"logMaxBackups": 10,
"logMaxAge": 30,
"mgAddrs": "127.0.0.1:27017",
"mgDbName": "go-microservices",
"mgDbUsername": "",
"mgDbPassword": "",
"jwtSecretPassword": "raycad",
"issuer": "seedotech"
}$ cd [go-microservices]/src/user-microservice
$ go run main.go
>> [GIN-debug] Listening and serving HTTP on :8808http://localhost:8808/swagger/index.html
NOTE: Using the default admin account admin/admin to authenticate the services
$ cd [go-microservices]/src/movie-microservice
$ go run main.go
>> [GIN-debug] Listening and serving HTTP on :8809http://localhost:8809/swagger/index.html
NOTE: Using the default admin account admin/admin to authenticate the services
3.1. Download the latest traefik
https://github.com/containous/traefik/releases/latest
3.2. Launch traefik
traefik.toml from [go-microservices]/traefik to traefik execution folder and update parameters.…$ ./traefik -c traefik.tomlTraefik dashboard
Now, assume that the Gateway IP is 192.168.1.8, then, when sending a request to the gateway like:
GET http://192.168.1.8:7777/seedotech.usermanagement/api/v1/movies/list
Gateway will route request to
GET http://192.168.1.9:8808/api/v1/movies/list
OR
GET http://192.168.1.10:8808/api/v1/movies/list
4.1. Successful response returns the application data through HTTP 200 OK Message
…4.2. Failed response returns the application error information (NOT HTTP 200 OK Message)
type Error struct {
Code int `json:"code" example:"27"`
Message string `json:"message" example:"Error message"`
}
Example:
// Returning HTTP StatusBadRequest (Code 400)
# @Failure 400 {object} models.Error
{
"code": -1,
"message": "User name is empty"
}
// Returning HTTP StatusNotFound (Code 404)
# @Failure 404 {object} models.Error
{
"code": -1,
"message": "User not found"
}go test toolname_linux.go will only build on linux, name_amd64.go will only build on amd64. This is the same as having a //+build amd64 line at the top of the fileDiscovery Service e.g. Eureka
Load Balancing e.g. Ribbon
Circuit Breaker e.g. Hystrix
Why do we need service registry?
The solution is to create the “telephone book” of services, called service registry.
Why are they used?
A circuit breaker is used to provide stability and prevent cascading failures in distributed systems. These should be used in conjunction with judicious timeouts at the interfaces between remote systems to prevent the failure of a single component from bringing down all components.
As an example, we have a web application interacting with a remote third party web service. Let’s say the third party has oversold their capacity and their database melts down under load. Assume that the database fails in such a way that it takes a very long time to hand back an error to the third party web service. This in turn makes calls fail after a long period of time. Back to our web application, the users have noticed that their form submissions take much longer seeming to hang. Well the users do what they know to do which is use the refresh button, adding more requests to their already running requests. This eventually causes the failure of the web application due to resource exhaustion. This will affect all users, even those who are not using functionality dependent on this third party web service.
Introducing circuit breakers on the web service call would cause the requests to begin to fail-fast, letting the user know that something is wrong and that they need not refresh their request. This also confines the failure behavior to only those users that are using functionality dependent on the third party, other users are no longer affected as there is no resource exhaustion. Circuit breakers can also allow savvy developers to mark portions of the site that use the functionality unavailable, or perhaps show some cached content as appropriate while the breaker is open.
Avoiding cascading failures with circuit breaker
Cascading failure can happen when multiple services are calling each other. For example if we have the below service topology
If service 1 fails then all other services will fail too. Additional risk is that Service 2 and 4 will keep sending requests to service 1, so it will be completely overloaded and will never be able to recover. The circuit breaker pattern addresses this problem. Just like an electrical switch, when closed electrons (requests) can flow through it, when open the flow is stopped. Hystrix can wrap methods with circuit breaker that uses the following logic :
What do they do?
1. During normal operation, a circuit breaker is in the Closed state:
2. While in Open state:
3. In Half-Open state:
4. State transition listeners:
5. Calls result listeners:
A typical scenario is when a REST client is wrapped with circuit breaker. The client makes a call to the backend, after subsequent exceptions the circuit opens and the fallback method is called that is serving a static content or an error message. Circuit breaker can be used in any place where there is a chance that operation will fail, but most often this is used in clients of external systems.
The Zuul API Gateway is part of the Netflix OSS package. It is very lightweight and integrates well with Eureka. API Gateway is the single entry point into the microservice ecosystem from the outside world.
Main features of Zuul
Zuul and NGINX are very similar the key differences are
**Eu
No open issues yet, or sync has not completed.