Skip to content

Commit

Permalink
example of rate limiting wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
henrod committed May 24, 2019
1 parent ae70329 commit 8b60c25
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ run-cluster-worker-example-worker:
run-custom-metrics-example:
@cd examples/demo/custom_metrics && go run main.go --port 3250

run-rate-limiting-example:
@go run examples/demo/rate_limiting/main.go

protos-compile:
@cd benchmark/testdata && ./gen_proto.sh
@protoc -I pitaya-protos/ pitaya-protos/*.proto --go_out=plugins=grpc:protos
Expand Down
53 changes: 53 additions & 0 deletions examples/demo/rate_limiting/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package main

import (
"flag"
"fmt"
"time"

"strings"

"github.com/spf13/viper"
"github.com/topfreegames/pitaya"
"github.com/topfreegames/pitaya/acceptor"
"github.com/topfreegames/pitaya/acceptorwrapper"
"github.com/topfreegames/pitaya/component"
"github.com/topfreegames/pitaya/config"
"github.com/topfreegames/pitaya/examples/demo/rate_limiting/services"
"github.com/topfreegames/pitaya/serialize/json"
)

func configureFrontend(port int) {
room := services.NewRoom()
pitaya.Register(room,
component.WithName("room"),
component.WithNameFunc(strings.ToLower))

// 5 requests in 1 minute. Doesn't make sense, just to test
// rate limiting
vConfig := viper.New()
vConfig.Set("pitaya.conn.ratelimiting.limit", 5)
vConfig.Set("pitaya.conn.ratelimiting.interval", time.Minute)
pConfig := config.NewConfig(vConfig)

tcp := acceptor.NewTCPAcceptor(fmt.Sprintf(":%d", port))
wrapped := acceptorwrapper.WithWrappers(
tcp,
acceptorwrapper.NewRateLimitingWrapper(pConfig))
pitaya.AddAcceptor(wrapped)
}

func main() {
defer pitaya.Shutdown()

port := flag.Int("port", 3250, "the port to listen")
svType := "room"

flag.Parse()

pitaya.SetSerializer(json.NewSerializer())
configureFrontend(*port)

pitaya.Configure(true, svType, pitaya.Cluster, map[string]string{})
pitaya.Start()
}
22 changes: 22 additions & 0 deletions examples/demo/rate_limiting/services/room.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package services

import (
"context"

"github.com/topfreegames/pitaya/component"
)

// Room represents a component that contains a bundle of room related handler
type Room struct {
component.Base
}

// NewRoom returns a new room
func NewRoom() *Room {
return &Room{}
}

// Ping returns a pong
func (r *Room) Ping(ctx context.Context) ([]byte, error) {
return []byte("pong"), nil
}

0 comments on commit 8b60c25

Please sign in to comment.