西维蜀黍

【Design Pattern】Microservices - Service Instance per Container Pattern

Context

You have applied the Microservice architecture pattern and architected your system as a set of services. Each service is deployed as a set of service instances for throughput and availability.

  ...


【Golang】源码 - sync 包 - Once

// /usr/local/go/src/sync/once.go

// Once is an object that will perform exactly one action.
type Once struct {
	// done indicates whether the action has been performed.
	// It is first in the struct because it is used in the hot path.
	// The hot path is inlined at every call site.
	// Placing done first allows more compact instructions on some architectures (amd64/x86),
	// and fewer instructions (to calculate offset) on other architectures.
	done uint32
	m    Mutex
}
  ...


【Golang】使用 - sync.Once

package main

import (
    "fmt"
    "sync"
)

var doOnce sync.Once

func main() {
    DoSomething()
    DoSomething()
}

func DoSomething() {
    doOnce.Do(func() {
        fmt.Println("Run once - first time, loading...")
    })
    fmt.Println("Run this every time")
}
  ...


【Golang】设计模式 - Creational - Singleton

Singleton Pattern

Refer to https://swsmile.info/post/design-pattern-singleton-pattern/ for Singleton pattern.

Using init() functions

Package init() functions are guaranteed to be called only once and all called from a single thread ( they’re thread-safe unless you make them multi-threaded). But that makes you dependent on boot order. And you should not write codes in an *init ( )* that you need a guarantee of execution at any given time

type A struct {
	str string
}

var singleton *A

func init() {
	//initialize static instance on load
	singleton = &A{str: "abc"}
}

//GetInstanceA - get singleton instance pre-initialized
func GetInstanceA() *A {
	return singleton
}
  ...


【Golang】Test - Unit Test Coverage

Test Coverage

Test coverage is a term that describes how much of a package’s code is exercised by running the package’s tests. If executing the test suite causes 80% of the package’s source statements to be run, we say that the test coverage is 80%.

  ...