search
HomeDatabaseMysql TutorialUsing MySQL to store cached data in Go language

In recent years, with the increasing amount of data processing, the demand for cache has become higher and higher. The traditional cache is based on memory storage. The advantage of this method is that it is fast, but the cost is high. The MySQL database is a moderately cost and highly reliable data storage method, so many companies choose to use MySQL to implement cache storage. This article will introduce how to use MySQL to store cached data in the Go language.

1. Use Go to operate MySQL database

1. Install the MySQL driver

In the Go language, we need to use the corresponding MySQL driver to perform database operations. Currently popular MySQL drivers include go-sql-driver/mysql, mysql/mysql-connector-go, gocraft/dbr, etc. Here, we choose to use go-sql-driver/mysql for example demonstration. If you use other MySQL drivers, it will not affect the execution of the following steps. First, we need to enter the following command in the terminal:

go get github.com/go-sql-driver/mysql

This command will install the go-sql-driver/mysql driver.

2. Connect to MySQL database

Below, we will implement a simple MySQL database connection program. In MySQL, you need to use a username and password to log in, so you need to prepare the corresponding MySQL username and password in advance. In this example, we set the username to root and the password to 123456. The code is as follows:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

const (
    username = "root"
    password = "123456"
    hostname = "127.0.0.1"
    port = 3306
    dbname = "test"
)

func main() {
    dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", username, password, hostname, port, dbname)
    db, err := sql.Open("mysql", dataSourceName)
    if err != nil {
        panic(err)
    }
    defer db.Close()
    err = db.Ping()
    if err != nil {
        panic(err)
    }
    fmt.Println("Successfully connected to the database!")
}

Note: Before running the program, please make sure that the MySQL service has been started.

After running the program, you can see the output as follows:

Successfully connected to the database!

This shows that we have successfully connected to the MySQL database.

2. Use MySQL to store cache data

Since MySQL is a relational database and cache is based on key-value pair storage, we need to store it in MySQL Create a table specifically for storing cache data. In this example, we created a table named cache_data, which contains 3 fields: key, value and expire_time. Among them, key and value represent the key and corresponding value respectively, and expire_time represents the expiration time of the data. The code is as follows:

CREATE TABLE `cache_data` (
  `key` varchar(255) NOT NULL DEFAULT '',
  `value` longblob NOT NULL,
  `expire_time` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

After the above SQL statement is completed, we can operate the MySQL database in Go language. Next, let's implement a simple cache example. The code is as follows:

package main

import (
    "database/sql"
    "fmt"
    "time"
    _ "github.com/go-sql-driver/mysql"
)

const (
    username = "root"
    password = "123456"
    hostname = "127.0.0.1"
    port = 3306
    dbname = "test"
)

type Cache struct {
    db *sql.DB
}

func (c *Cache) Set(key string, value []byte, expireTime time.Duration) error {
    query := fmt.Sprintf("INSERT INTO cache_data (key, value, expire_time) VALUES ('%s', ?, %d) ON DUPLICATE KEY UPDATE value = ?", key, time.Now().Add(expireTime).Unix())
    stmt, err := c.db.Prepare(query)
    if err != nil {
        return err
    }
    _, err = stmt.Exec(value, value)
    if err != nil {
        return err
    }
    return nil
}

func (c *Cache) Get(key string) ([]byte, error) {
    var value []byte
    query := fmt.Sprintf("SELECT value, expire_time FROM cache_data WHERE key = '%s'", key)
    err := c.db.QueryRow(query).Scan(&value)
    if err != nil {
        return nil, err
    }
    return value, nil
}

func NewCache() (*Cache, error) {
    dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", username, password, hostname, port, dbname)
    db, err := sql.Open("mysql", dataSourceName)
    if err != nil {
        return nil, err
    }
    err = db.Ping()
    if err != nil {
        return nil, err
    }
    cache := &Cache{
        db: db,
    }
    return cache, nil
}

func main() {
    cache, err := NewCache()
    if err != nil {
        panic(err)
    }
    err = cache.Set("key1", []byte("value1"), time.Second*10)
    if err != nil {
        panic(err)
    }
    value, err := cache.Get("key1")
    if err != nil {
        panic(err)
    }
    fmt.Println(string(value))
}

In the above code, we implement a Cache structure, which contains three methods: Set, Get and NewCache. Among them, the Set method is used to store key-value pairs into the MySQL database; the Get method is used to obtain the value of the specified key; the NewCache method is used to initialize the Cache structure. In this example, we set the value of key "key1" to "value1" and specify the expiration time to be 10 seconds. Then we call the Get method to obtain the value of key "key1" and print it.

After running the program, you can see the output as follows:

value1

This shows that we have successfully implemented a cache storage using MySQL.

Summary

This article introduces how to use MySQL to store cached data in the Go language. The specific steps include using the go-sql-driver/mysql driver to connect to the MySQL database. In MySQL Create a table specifically used to store cache data to implement cache storage, etc. Through the introduction of this article, we can see that using MySQL as a cache storage method has the advantages of low cost and high reliability, and is a very recommended practice method.

The above is the detailed content of Using MySQL to store cached data in Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.