SoFunction
Updated on 2025-04-14

Detailed explanation of the example of starting Redis using Go language

I have written several articles related to Go concurrent programming recently. I believe some readers may get tired of reading too much. Today I will give some easy content to introduce one that can be used to start.redis-serverOpen source library/stvp/tempredis. This is a package developed in Go, designed specifically for creating temporary Redis instances, mainly for testing purposes. It can start a temporary Redis service instance locally, automatically close and clean after testing, helping developers avoid operating on the actual Redis environment.

Main functions

tempredisThe main functions of the package are as follows:

  • Quickly start a temporary Redis instance: no manual installation and configuration of Redis is required, as long as the Redis binary is already installed on the system (redis-server)。
  • Independent test environment: Each test runs an independent Redis instance, avoiding mutual interference between tests.
  • Automatic cleaning: After the test is completed, the temporary instance will be closed and the relevant files will be deleted.

Environmental preparation

First of all, of course, you need to install Redis binary files and install them on the host.tempredisGo package:

# Use brew directly on mac computer to install redis-server# For other platforms, please refer to the official document: /docs/latest/operate/oss_and_stack/install/install-redis/$ brew install redis
# Install the tempredis Go package$ go get -u /stvp/tempredis

Brief introduction

Can betempredis documentationSee the exported structure and methods that it implements:

type Config
    func (c Config) Socket() string
type Server
    func Start(config Config) (server *Server, err error)
    func (s *Server) Kill() (err error)
    func (s *Server) Socket() string
    func (s *Server) Stderr() string
    func (s *Server) Stdout() string
    func (s *Server) Term() (err error)

ConfigThe structure is actually onemap[string]stringObject, used to set Redis configuration. ItsSocketMethods are used to returnFile location.

ServerThe structure represents a Redis instance object, and the functions of several methods are as follows:

  • Startis a function that is used according to the given configurationConfigstart upServer
  • KillMethod for force closingredis-server
  • TermMethod for elegant closingredis-server
  • SocketThe method will be proxyed toMethod call.
  • StdoutMethod blocking and waiting for returnredis-serverStandard output after execution.
  • StderrMethod blocking and waiting for returnredis-serverError output after execution.

Example of usage

We've gotten ittempredisWith a preliminary understanding of the provided methods, it is time to write a small demo to practice. The sample code is as follows:

package main

import (
	"fmt"
	"log"
	"time"

	"/go-redis/redis"
	"/stvp/tempredis"
)

func main() {
	// Create and start a temporary Redis instance	server, err := ({
		"port": "0", // Automatically allocate ports	})
	if err != nil {
		("Failed to start tempredis: %v", err)
	}

	// Place it in defer to avoid blocking main goroutine	defer func() {
		("====================== stdout ======================")
		(())
		("====================== stderr ======================")
		(())
	}()

	// Close redis-server when main exits	defer ()

	// Get the address of Redis	("Redis server is running at", ())

	// Connect to temporary Redis instances	client := (&{
		Network: "unix",
		Addr:    (),
	})

	// Use Redis instance	("name", "jianghushinian", )
	val, err := ("name").Result()
	if err != nil {
		("Get redis key error:", err)
		return
	}
	("name:", val)

	()

	// After 1s, name has expired	val, err = ("name").Result()
	if err != nil {
		("Get redis key error:", err)
		return
	}
	("name:", val)
}

I wrote comments and instructions for each part of the code, which is not difficult to understand. After starting a temporary Redis instance, you can use any Go Redis client to connect, usinggo-redis/redis. After that, you can use Redis functions normally.

Execute the sample code and get the output as follows:

$ go run
Redis server is running at /var/folders/_n/xb14yhv56fq98c_nqcg8skfc0000gp/T/tempredis1387753332/
name: jianghushinian
Get redis key error: redis: nil
====================== stdout ======================
31048:C 02 Jan 2025 00:24:23.933 * Reading config from stdin
31048:C 02 Jan 2025 00:24:23.933 * oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
31048:C 02 Jan 2025 00:24:23.933 * Redis version=7.2.6, bits=64, commit=00000000, modified=0, pid=31048, just started
31048:C 02 Jan 2025 00:24:23.933 * Configuration loaded
31048:M 02 Jan 2025 00:24:23.933 * monotonic clock: POSIX clock_gettime
31048:M 02 Jan 2025 00:24:23.934 * Running mode=standalone, port=0.
31048:M 02 Jan 2025 00:24:23.934 # WARNING: The TCP backlog setting of 511 cannot be enforced because is set to the lower value of 128.
31048:M 02 Jan 2025 00:24:23.934 * Server initialized
31048:M 02 Jan 2025 00:24:23.934 * Loading RDB produced by version 7.2.6
31048:M 02 Jan 2025 00:24:23.934 * RDB age 167 seconds
31048:M 02 Jan 2025 00:24:23.934 * RDB memory usage when created 1.11 Mb
31048:M 02 Jan 2025 00:24:23.934 * Done loading RDB, keys loaded: 0, keys expired: 0.
31048:M 02 Jan 2025 00:24:23.934 * DB loaded from disk: 0.000 seconds
31048:M 02 Jan 2025 00:24:23.934 * Ready to accept connections unix
31048:signal-handler (1735748664) Received SIGTERM scheduling shutdown...
31048:M 02 Jan 2025 00:24:24.944 * User requested shutdown...
31048:M 02 Jan 2025 00:24:24.944 * Saving the final RDB snapshot before exiting.
31048:M 02 Jan 2025 00:24:24.954 * DB saved on disk
31048:M 02 Jan 2025 00:24:24.954 * Removing the unix socket file.
31048:M 02 Jan 2025 00:24:24.954 # Redis is now ready to exit, bye bye...
====================== stderr ======================

This example is a good demonstrationtempredisThe only function and usage ofThe method is now, you can try it yourself.

Summarize

This article describes how to use ittempredisPackage to start Redis instances and apply them to Go projects. Can be found,tempredisThe function and usage of the package are very simple.

The reason why this package was introduced is actually because it appeared inredsyncIn the project, this is a Redis distributed lock implemented in Go language. Interested readers can study it on their own.

This is the end of this article about the detailed explanation of the example of using Go to start Redis. For more related content on Go to start Redis, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!