Skip to content

Latest commit

 

History

History

08

Routing the Cache

In this part, you'll route requests to the Cache component so that repeated requests for the same query are routed to the same replica. Review the documentation on routing. In cache.go, implement a routing struct called router that routes Get and Put requests using the query as the routing key.

Solution.

workshops/08/cache.go

Lines 63 to 74 in 4eca79e

// router routes requests to the Cache component. Both Get and Put use the
// query as the routing key. Calls to these methods with the same query will
// tend to be routed to the same replica.
type router struct{}
func (router) Get(_ context.Context, query string) string {
return query
}
func (router) Put(_ context.Context, query string, _ []string) string {
return query
}

Embed weaver.WithRouter[router] in your cache implementation to enable routing.

Solution.

workshops/08/cache.go

Lines 34 to 41 in 4eca79e

// cache implements the Cache component.
type cache struct {
weaver.Implements[Cache]
weaver.WithRouter[router]
mu sync.Mutex
emojis map[string][]string
}

Build and run your application using weaver multi deploy:

$ weaver generate .
$ go build .
$ weaver multi deploy config.toml

And again in a separate terminal, repeatedly curl the application.

$ curl "localhost:9000/search?q=pig"
["🐖","🐗","🐷","🐽"]
$ curl "localhost:9000/search?q=pig"
["🐖","🐗","🐷","🐽"]
$ curl "localhost:9000/search?q=pig"
["🐖","🐗","🐷","🐽"]
$ curl "localhost:9000/search?q=pig"
["🐖","🐗","🐷","🐽"]

The first request should be slow, but all subsequent requests should complete nearly instantly. If you look at your application logs, you can confirm that Get and Put requests for the query "pig" are routed to the same Cache replica. Here are the logs for the /search?q=pig requests above:

emojis.Searcher 1da63c0a searcher.go:53] Search query="pig"
emojis.Cache    e1ef982f cache.go:51   ] Get query="pig"
emojis.Cache    e1ef982f cache.go:58   ] Put query="pig"
emojis.Searcher 2dc51d83 searcher.go:53] Search query="pig"
emojis.Cache    e1ef982f cache.go:51   ] Get query="pig"
emojis.Searcher 1da63c0a searcher.go:53] Search query="pig"
emojis.Cache    e1ef982f cache.go:51   ] Get query="pig"
emojis.Searcher 2dc51d83 searcher.go:53] Search query="pig"
emojis.Cache    e1ef982f cache.go:51   ] Get query="pig"

Notice that every Get and Put is routed to replica e1ef982f. At this point, feel free to remove the time.Sleep(time.Second) call from your code.

⬅️ Previous Part     ⚫     Next Part ➡️