Home Database Mysql Tutorial Using MySQL to store cached data in Go language

Using MySQL to store cached data in Go language

Jun 17, 2023 pm 06:17 PM
mysql cache 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
Copy after login

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!")
}
Copy after login

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!
Copy after login

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;
Copy after login

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))
}
Copy after login

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
Copy after login

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 of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

Steps to add and delete fields to MySQL tables Steps to add and delete fields to MySQL tables Apr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Detailed explanation of the installation steps of MySQL on macOS system Detailed explanation of the installation steps of MySQL on macOS system Apr 29, 2025 pm 03:36 PM

Installing MySQL on macOS can be achieved through the following steps: 1. Install Homebrew, using the command /bin/bash-c"$(curl-fsSLhttps://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)". 2. Update Homebrew and use brewupdate. 3. Install MySQL and use brewinstallmysql. 4. Start MySQL service and use brewservicesstartmysql. After installation, you can use mysql-u

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

See all articles