12/04/2026 18:18pm

Ep.20 Go and Caching Enhancing Program Speed!
#Superdev School
#programmer
#programming
#programming for beginners
#programmer learning
#programming language
#programmer education
#learning programming
#Programming Class
#Programming Education
#Practice programming
#Go language
#Golang
#Go Programming
#Go
Go and Caching: Enhancing Program Speed
What is Caching?
Caching is the process of storing certain data in memory so that it can be accessed quickly without having to retrieve it from the original source repeatedly. For example, storing frequently accessed results from a database in memory allows a program to load data faster.
Benefits of Caching
1. Increased Speed: Reduces the need to fetch data from external sources (like databases), enhancing data access speed.
2. Resource Efficiency: Minimizes redundant data retrieval, thereby reducing system workload.
3. Ideal for Static Data: Particularly suitable for data that does not change frequently, such as product listings, default values, etc.
Creating a Simple Cache Using Map in Go
In Go, we can create a simple cache using a map, which serves to store data in memory and allows for quick data retrieval.
Example of a Simple Cache:
In this example, we define a Cache struct that contains a map for storing data. The Set method is used to store data in the cache, while the Get method retrieves data from the cache.
package main
import (
"fmt"
)
type Cache struct {
data map[string]string
}
func (c *Cache) Set(key, value string) {
c.data[key] = value
}
func (c *Cache) Get(key string) (string, bool) {
value, found := c.data[key]
return value, found
}
func main() {
cache := Cache{data: make(map[string]string)}
cache.Set("name", "Alice")
cache.Set("country", "Thailand")
if value, found := cache.Get("name"); found {
fmt.Println("Cached value:", value)
} else {
fmt.Println("Value not found in cache")
}
}
Setting Expiration Time for Cache (TTL - Time to Live)
Sometimes, we want cached data to expire after a certain period to ensure that the information being used is up-to-date.
Example Code for Setting TTL in Cache:
In this example:
We add an expiration time to the cached data using time.Now().Add(ttl).Unix() to define the expiry time.
When checking the data in the cache, we verify whether the expiration time has passed. If it has expired, we consider that the data is no longer available in the cache.
This approach helps maintain the freshness of the data while still benefiting from the speed of caching.
package main
import (
"fmt"
"time"
)
type CacheItem struct {
value string
expiration int64
}
type Cache struct {
data map[string]CacheItem
}
func (c *Cache) Set(key, value string, ttl time.Duration) {
expiration := time.Now().Add(ttl).Unix()
c.data[key] = CacheItem{value: value, expiration: expiration}
}
func (c *Cache) Get(key string) (string, bool) {
item, found := c.data[key]
if !found || time.Now().Unix() > item.expiration {
return "", false
}
return item.value, true
}
func main() {
cache := Cache{data: make(map[string]CacheItem)}
cache.Set("session_id", "abc123", 5*time.Second)
if value, found := cache.Get("session_id"); found {
fmt.Println("Cached value:", value)
} else {
fmt.Println("Value not found in cache or expired")
}
time.Sleep(6 * time.Second) // รอให้ Cache หมดอายุ
if value, found := cache.Get("session_id"); found {
fmt.Println("Cached value:", value)
} else {
fmt.Println("Value not found in cache or expired")
}
}
Example of Using Cache in Real Applications
In real applications, caching is often used for data that does not change frequently, such as user information, products, or settings. This allows programs to retrieve data faster and reduces redundant loads from the database.
In Summary:
- Cache Increases Speed: It stores frequently accessed data to minimize repeated loading.
- Set TTL: Configure the cache to expire after a specified time to mitigate issues with outdated information.
- Use Map in Go for Cache: Maps enable quick data retrieval, making them ideal for caching purposes.