Skip to content

Instantly share code, notes, and snippets.

@XUJiahua
Created October 18, 2018 07:30
Show Gist options
  • Save XUJiahua/4457e4358cf2957220c573f6edd6ea06 to your computer and use it in GitHub Desktop.
Save XUJiahua/4457e4358cf2957220c573f6edd6ea06 to your computer and use it in GitHub Desktop.
proxy = struct embedding + interface
package embintf
import (
"github.com/sirupsen/logrus"
"time"
)
type Cat struct {
ID int64
}
type CatRepo interface {
Get(id int64) (*Cat, error)
Set(cat *Cat) error
}
// db impl
type dbCatRepo struct{}
// inject dependencies
func NewDBCatRepo(conn string) *dbCatRepo {
return &dbCatRepo{}
}
func (dbCatRepo) Get(id int64) (*Cat, error) {
logrus.Debug("reading from DB")
time.Sleep(time.Microsecond * 200)
return &Cat{id}, nil
}
func (dbCatRepo) Set(cat *Cat) error {
logrus.Debug("writing to DB")
time.Sleep(time.Second)
return nil
}
// proxy by embedding + interface
// cache proxy impl
type cachedCatRepo struct {
*dbCatRepo
cache map[int64]*Cat
}
// inject dependencies
func NewCachedCatRepo(mCatRepo *dbCatRepo) *cachedCatRepo {
return &cachedCatRepo{
dbCatRepo: mCatRepo,
cache: make(map[int64]*Cat),
}
}
// overwrite
func (r cachedCatRepo) Get(id int64) (*Cat, error) {
logrus.Debug("reading from cache")
if cat, ok := r.cache[id]; ok {
return cat, nil
}
cat, err := r.dbCatRepo.Get(id)
if err != nil {
return nil, err
}
logrus.Debug("writing to cache")
r.cache[id] = cat
return cat, nil
}
package embintf
import (
"testing"
)
// BenchmarkCachedCatRepo_Get-8 100000000 12.2 ns/op
func BenchmarkCachedCatRepo_Get(b *testing.B) {
mCatRepo := NewDBCatRepo("127.0.0.1:3306")
rCatRepo := NewCachedCatRepo(mCatRepo)
benchmark(b, rCatRepo)
}
// BenchmarkDbCatRepo_Get-8 5000 267805 ns/op
func BenchmarkDbCatRepo_Get(b *testing.B) {
mCatRepo := NewDBCatRepo("127.0.0.1:3306")
benchmark(b, mCatRepo)
}
func benchmark(b *testing.B, repo CatRepo) {
for i := 0; i < b.N; i++ {
repo.Get(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment