Skip to content

Commit

Permalink
[Improve] improve the perf of schema and schema cache (#1033)
Browse files Browse the repository at this point in the history
* [Improve] improve the perf of schema and schema cache

* [Fix] fix lint error

* [revert] revert comment format

* [revert] revert comment format

* use sync.Once instead of atomic.Uint64

* revert comment format

---------

Co-authored-by: gunli <gunli@tencent.com>
  • Loading branch information
gunli and gunli committed Jul 4, 2023
1 parent 5f8df27 commit 163cd7e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 18 deletions.
21 changes: 8 additions & 13 deletions pulsar/producer_partition.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,29 +100,24 @@ type partitionProducer struct {
}

type schemaCache struct {
lock sync.RWMutex
schemas map[uint64][]byte
schemas sync.Map
}

func newSchemaCache() *schemaCache {
return &schemaCache{
schemas: make(map[uint64][]byte),
}
return &schemaCache{}
}

func (s *schemaCache) Put(schema *SchemaInfo, schemaVersion []byte) {
s.lock.Lock()
defer s.lock.Unlock()

key := schema.hash()
s.schemas[key] = schemaVersion
s.schemas.Store(key, schemaVersion)
}

func (s *schemaCache) Get(schema *SchemaInfo) (schemaVersion []byte) {
s.lock.RLock()
defer s.lock.RUnlock()

return s.schemas[schema.hash()]
val, ok := s.schemas.Load(schema.hash())
if !ok {
return nil
}
return val.([]byte)
}

func newPartitionProducer(client *client, topic string, options *ProducerOptions, partitionIdx int,
Expand Down
17 changes: 12 additions & 5 deletions pulsar/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"fmt"
"hash/maphash"
"reflect"
"sync"
"unsafe"

log "github.com/sirupsen/logrus"
Expand Down Expand Up @@ -66,13 +67,19 @@ type SchemaInfo struct {
Schema string
Type SchemaType
Properties map[string]string
hashVal uint64
hashOnce sync.Once
}

func (s SchemaInfo) hash() uint64 {
h := maphash.Hash{}
h.SetSeed(seed)
h.Write([]byte(s.Schema))
return h.Sum64()
func (s *SchemaInfo) hash() uint64 {
s.hashOnce.Do(func() {
h := maphash.Hash{}
h.SetSeed(seed)
h.Write([]byte(s.Schema))
s.hashVal = h.Sum64()
})

return s.hashVal
}

type Schema interface {
Expand Down

0 comments on commit 163cd7e

Please sign in to comment.