Home  >  Article  >  Database  >  Using MySQL to store cached data in Go language

Using MySQL to store cached data in Go language

WBOY
WBOYOriginal
2023-06-17 18:17:13898browse

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