Ver código fonte

Fix cache test (Fiber v1.12) (#5816)

* Update Fiber v1.10.0

* Fiber: Bump v1.12.0

* Update constant

* Fiber optimization

* v1.12.1

* Update dependencies

* Update cached worlds test

* Update cached test

* Update cached test

* Update cache test

* Fix cache test

* Update cache test

* Update cache test

* Fix panic

Co-authored-by: Fenny <Fenny>
fenny 5 anos atrás
pai
commit
b197b1cbe6
1 arquivos alterados com 32 adições e 21 exclusões
  1. 32 21
      frameworks/Go/fiber/src/server.go

+ 32 - 21
frameworks/Go/fiber/src/server.go

@@ -18,8 +18,9 @@ import (
 )
 
 var (
-	child bool
-	db    *pgxpool.Pool
+	child        bool
+	db           *pgxpool.Pool
+	cachedWorlds Worlds
 )
 
 const (
@@ -28,7 +29,7 @@ const (
 	helloworld       = "Hello, World!"
 	worldselectsql   = "SELECT id, randomNumber FROM World WHERE id = $1"
 	worldupdatesql   = "UPDATE World SET randomNumber = $1 WHERE id = $2"
-	worldcachesql    = "SELECT * FROM World"
+	worldcachesql    = "SELECT * FROM World LIMIT $1"
 	fortuneselectsql = "SELECT id, message FROM Fortune"
 )
 
@@ -112,7 +113,7 @@ func ReleaseWorld(w *World) {
 // WorldsPool ...
 var WorldsPool = sync.Pool{
 	New: func() interface{} {
-		return make(Worlds, 0, 512)
+		return make(Worlds, 0, 500)
 	},
 }
 
@@ -144,6 +145,27 @@ func initDatabase() {
 	if err != nil {
 		panic(err)
 	}
+	populateCache()
+}
+
+// this will populate the cached worlds for the cache test
+func populateCache() {
+	worlds := make(Worlds, worldcount)
+	rows, err := db.Query(context.Background(), worldcachesql, worldcount)
+	if err != nil {
+		panic(err)
+	}
+	for i := 0; i < worldcount; i++ {
+		w := &worlds[i]
+		if !rows.Next() {
+			break
+		}
+		if err := rows.Scan(&w.ID, &w.RandomNumber); err != nil {
+			panic(err)
+		}
+		//db.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)
+	}
+	cachedWorlds = worlds
 }
 
 // jsonHandler :
@@ -226,26 +248,15 @@ func plaintextHandler(c *fiber.Ctx) {
 	c.SendString(helloworld)
 }
 
-var cachePopulated = false
-var catchedWorlds []World
-
-func populateCache() {
-	worlds := AcquireWorlds()[:500]
-	for i := 0; i < 500; i++ {
-		w := &worlds[i]
-		db.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)
-	}
-	catchedWorlds = worlds
-	cachePopulated = true
-}
-
 // cachedHandler :
 func cachedHandler(c *fiber.Ctx) {
-	if !cachePopulated {
-		populateCache()
-	}
 	n := QueriesCount(c)
-	c.JSON(catchedWorlds[:n])
+	worlds := AcquireWorlds()[:n]
+	for i := 0; i < n; i++ {
+		worlds[i] = cachedWorlds[RandomWorld()-1]
+	}
+	c.JSON(worlds)
+	ReleaseWorlds(worlds)
 }
 
 // RandomWorld :