Simple In-Memory Key-Value Store in Go with Concurrency Handling
Creating a key-value store in Go (Golang) can be a fun and educational project. Below is a simple implementation of an in-memory key-value store. This basic implementation includes functions to set, get, and delete key-value pairs. It uses a map
as the underlying data structure and includes mutex synchronization to handle concurrent access.
package main
import (
"fmt"
"sync"
)
// KVStore represents a key-value store.
type KVStore struct {
store map[string]interface{}
mu sync.RWMutex
}
// NewKVStore creates a new KVStore.
func NewKVStore() *KVStore {
return &KVStore{
store: make(map[string]interface{}),
}
}
// Set adds a key-value pair to the store.
func (kv *KVStore) Set(key string, value interface{}) {
kv.mu.Lock()
defer kv.mu.Unlock()
kv.store[key] = value
}
// Get retrieves a value by key from the store.
func (kv *KVStore) Get(key string) (interface{}, bool) {
kv.mu.RLock()
defer kv.mu.RUnlock()
value, exists := kv.store[key]
return value, exists
}
// Delete removes a key-value pair from the store.
func (kv *KVStore) Delete(key string) {
kv.mu.Lock()
defer kv.mu.Unlock()
delete(kv.store, key)
}
func main() {
// Create a new key-value store
store := NewKVStore()
// Set some key-value pairs
store.Set("name", "Alice")
store.Set("age", 30)
// Retrieve a value
if value, exists := store.Get("name"); exists {
fmt.Println("Name:", value)
} else {
fmt.Println("Name not found")
}
// Delete a key-value pair
store.Delete("name")
// Try to retrieve the deleted key
if value, exists := store.Get("name"); exists {
fmt.Println("Name:", value)
} else {
fmt.Println("Name not found")
}
}
Explanation:
-
KVStore Structure: The
KVStore
struct contains the map which holds the key-value pairs and ansync.RWMutex
to handle concurrent access. -
NewKVStore Function: This function initializes and returns a new
KVStore
. -
Set Method: Adds a key-value pair to the store. It locks the store to prevent concurrent write operations.
-
Get Method: Retrieves the value associated with a given key. It uses a read lock to allow concurrent read access but prevent write access during the read operation.
-
Delete Method: Removes a key-value pair from the store. It locks the store to prevent concurrent write operations.
-
Main Function: Demonstrates how to use the key-value store by setting, getting, and deleting key-value pairs.
This example is simple and does not cover persistence, eviction, or other advanced features found in production-ready key-value stores.
Other Xegs
- HTTP Zig Server
Simple HTTP server
- Airbnb API
Property managers
- Okta migration
Fetching all users
- Zig Stack vs Heap
Memory management