一个简单的 Golang 项目模板,遵循 Go 社区最佳实践
This project serves as a boilerplate for managing and processing tasks using background workers, with tasks stored in a database. While the tasks provided are placeholders within the pkg folder, they demonstrate how you can implement similar functionality in your own projects. For instance, the project includes sample tasks like send email and run query. These tasks are intentionally simplified—they merely simulate activity by running a sleep function and occasionally failing. The failures are deliberate, allowing you to explore error handling and implement retries when necessary.
This is a sample project designed to be run locally. My goal in creating this repository is to provide a code template that:
.env.template file that you can use to control env variables for your application. Make a copy of this file with the name .env and it will be loaded automatically.Makefile contains 3 commands: deps, build, and test../db/migrations folder.API docs are available in the api directory, and you could open them using swagger UI by the following command from the root of the project:
docker run -p 8081:8080 -e SWAGGER_JSON=/api/swagger.yaml -v $(pwd)/api:/api swaggerapi/swagger-uiby doing so, you could head to http://localhost:8081 to see the API docs
Or if you use IntelliJ Goland, you could see the file in its Swagger UI tool.
Application consists of 3 parts:
Before running the application, make sure you have set correct env variables in the .env file.
This file contains PostgreSQL credentials, RabbitMQ credentials, Redis Credentials, etc.
After making sure the env file is OK, you have to source it before running the app, this way all env variables will be set.
source .envThis part serves APIs to be accessible using HTTP interface. You could run this part either by running the following command:
go run cmd/server/main.goOr by building application and then running the server binary as follows:
make build
./bin/serverThere is job workers in the cmd/worker directory.
The reason I've separated them is:
I have used RabbitMQ here; When a task is created through API, it's serialized and pushed to a jobs queue, then the worker(s) are able to pop the task from the queue and process that.
I have used 4 queues:
high prioritynormal prioritylow priorityintegration testing which won't be used on productionI have worked with Redis queues in high loads, and it's not efficient in high loads, Also I thought that using Kafka would be considered as over-engineering for this case. So, I preferred to use Rabbit Pub/Sub.
I also have used Redis as distributed lock infrastructure in the workers. When the worker starts to process a task, It locks a key to make sure that other workers can't process and are not processing that task simultaneously.
Although the code doesn't push a task multiple times to the queue, I also considered this case.
Each Worker has a number that must be unique. numbers could start from 1 to the infinite. When you want to run a worker, you could run the following command:
go run cmd/worker/main.go $priority $workerNumberPriority could be of high, normal or low.
Example:
go run cmd/worker/main.go normal 1Or you could build the app (if you haven't built that before), and use the binary as follows:
./bin/job_worker $priority $workerNumberThis way and by using a queue, we could easily scale the number of workers if load is high without increasing pressure on the PostgreSQL.
I've considered durability of RabbitMQ to be true.
But, In case that data of the queue has been lost or some tasks have got out of the queue, you could run this command as follows:
go run cmd/recovery/main.go $taskStatus $pastSeconds $limitor
./bin/queue_recovery $taskStatus $pastSeconds $limitParameters definitions:
queued or failed because running or succeeded jobs are not supposed to be re-queued.updated_at field of the task is not changed (It fetches tasks with the given status which are not updated in the last X seconds)Normally this command is not needed to be run, it's just been developed for emergency cases.
As mentioned before, the needed scripts for building the app are developed in the make file, so all you need is to run:
make buildWhenever you change the code, and then, binaries will be available in the bin directory of the project.
There is a Dockerfile developed for building the docker file of the app. You can make a new docker image of the application using the following command:
make dockerIn this Dockerfile, all binaries (server, job_worker, queue_recovery) are placed into one image. In the future, If the size of binaries goes high, we could have different Dockerfiles for different usages(one for appserver, one for workers, one for recovery). But, here for the sake of simplicity, I've put all binaries in one Dockerfile.
After you made the docker image, the make docker command will let you know the name of created image.
Then, you have to:
kind load docker-image $dockerImageNamek8s files: there are Kubernetes deployment files placed in the k8s/deployment directory.
You have to update the docker image (image) field of these files to the newly created image.You have to setup a local cluster using kind if you haven't done that.
You should install kind and then run the following command:
kind create clusterYou should deploy PostgreSQL, Redis, and RabbitMQ.
To have them deployed on the same Kubernetes cluster, you could use helm.
Make sure you have installed it and then run the following commands.
At the end of each command, it will show you Readmes to know how to find out their credentials.
So, please write them down for each step(infra), As we need them in the next step.
Commands to deploy these infras are:
helm install my-postgresql oci://registry-1.docker.io/bitnamicharts/postgresql
helm install my-rabbit oci://registry-1.docker.io/bitnamicharts/rabbitmq
helm install my-redis oci://registry-1.docker.io/bitnamicharts/redisProject configs are placed in the k8s/helm_charts/myvalues.yaml file down to env: section.
Make sure you have set current configs here.
Note!: Here I've placed important data like Database credentials here, but in production environments, you'd better store them as secrets for more security.
I have developed helm charts for deployment of server and workers. I have used Helm charts because there are lots of repetitious things in this kube files and using Helm is better. Before helm, I had used K8s files which are available in my previous commits (you could look at them). I replaced them with helm charts.
To deploy the Appserver, you have to run:
helm upgrade --install appserver ./k8s/helm_charts -f ./k8s/helm_charts/myvalues.yamlTo deploy workers you have to run these commands:
helm upgrade --install jobworker-high-1 ./k8s/helm_charts/ -f ./k8s/helm_charts/myvalues.yaml -f ./k8s/helm_charts/myvalues_job_worker_high_1.yaml
helm upgrade --install jobworker-normal-1 ./k8s/helm_charts/ -f ./k8s/helm_charts/myvalues.yaml -f ./k8s/helm_charts/myvalues_job_worker_normal_1.yaml
helm upgrade --install jobworker-low-1 ./k8s/helm_charts/ -f ./k8s/helm_charts/myvalues.yaml -f ./k8s/helm_charts/myvalues_job_worker_low_1.yamlIn the next step, Make sure the pods of both commands are working, by listing their pods and then checking their state (their state must be Running).
You should also check their logs by using the following command:
kubectl logs -f $podNameFor finding the pod names you could run the following command:
kubectl get podsThe pod names are the same as deployment names plus some added hash suffixes.
If there are problems you should see the logs and be able to resolve it. If everything works, go to the next stage
To expose the service in production environment, you should connect the service of appserver to the ingress to connect it to the external edge of the infra.
But here on your local cluster, you don't need to do so. You could just expose the created service for the server app to be connected to specific port of your localhost.
To do so, you could run the following command:
kubectl port-forward svc/appserver-myapp 8080:8086This command will map the port 8080 of your local machine to the port 80 of the server service.
Now you can access your app server by sending your requests to http://localhost:8080.
If you made changes to the code, then in order to deploy your changes to Kubernetes, you need to:
1 - Build again your application (make build)
2 - Create new Docker image (make docker)
3 - Load new image in Kind (kind load docker-image $newDockerImage)
4 - Update image version in the k8s/helm_charts/myvalues.yaml file version field.
For example, if your image name is task-manager:v23123-8, you should set the version field to v23123-8.
4 - Update helm charts.
For Appserver, you have to run the following command:
helm upgrade --install appserver ./k8s/helm_charts -f ./k8s/helm_charts/myvalues.yamlFor workers you should do as follows:
helm upgrade --install jobworker-high-1 ./k8s/helm_charts/ -f ./k8s/helm_charts/myvalues.yaml -f ./k8s/helm_charts/myvalues_job_worker_high_1.yaml
helm upgrade --install jobworker-normal-1 ./k8s/helm_charts/ -f ./k8s/helm_charts/myvalues.yaml -f ./k8s/helm_charts/myvalues_job_worker_normal_1.yaml
helm upgrade --install jobworker-low-1 ./k8s/helm_charts/ -f ./k8s/helm_charts/myvalues.yaml -f ./k8s/helm_charts/myvalues_job_worker_low_1.yamlAfter this step, just recheck that you may need to rerun kubectl port-forward ... command.
All done!
I've provided you with the build_and_deploy.sh script. all you need is to run that. But make sure you have created the infra by doing the previous steps before running this script.
This script is a sample of what CI/CD does, but it's written in bash to be able to be run locally.
Note: If you've created new deployments (new helm files), make sure to update this script and add those stages.
Note: In production, for providing au
暂无开放 Issues,或尚未同步最近议题。