Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of implementing two-level cache by MySQL and Redis

2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to achieve secondary caching in MySQL and Redis. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Introduction to redis

Redis is completely open source and free, complies with BSD protocol, and is a high-performance key-value database.

Redis and other key-value cache products have the following three features:

Redis supports data persistence. Data in memory can be saved on disk and can be loaded and used again when rebooting.

Redis not only supports simple key-value type data, but also provides storage of data structures such as list,set,zset,hash.

Redis supports data backup, that is, data backup in master-slave mode.

advantage

Extremely high performance-Redis can read 110000 times per second and write 81000 times per second

Rich data types-Redis supports Strings, Lists, Hashes, Sets and Ordered Sets data type operations for binary cases

Atom-all operations of Redis are atomic, meaning either successful execution or failure to execute at all. A single operation is atomic. Multiple operations also support transactions, that is, atomicity, wrapped by MULTI and EXEC instructions

Download and install

Download and extract

Wget http://download.redis.io/releases/redis-5.0.3.tar.gztar xzf redis-5.0.3.tar.gz

Move the folder to / usr/local/

Mv redis-5.0.3 / usr/local/

Go to the folder and compile the test

Cd / usr/local/redis-5.0.3sudo make test

Compilation and installation

Sudo make install

Start redis

Redis-server

If the following screen appears, the redis database has been started:

Jpg

Mysql and redis do secondary cache

For the data with large access volume, we need to cache the data obtained in the database in order to obtain the data more quickly.

Using the Redis caching process in a project

Data caching should consider the problem of synchronization: if the data is cached, when querying the data, if there is data in the cache, the cached data will not be queried directly. The problem of database inconsistency may occur when the database data changes. You can consider deleting the corresponding cached data each time you modify the database, so that the database will be queried and cached when you re-query.

When querying, first query from the cache

If there is no data in the cache, query it from the database and save the data in the cache.

If the data is queried in the cache and returned directly, there is no need to query the database.

Step realization

Create redisPool.go files for initialization of connection pooling

Package redigo_poolimport ("flag"github.com/garyburd/redigo/redis"time") var (Pool * redis.Pool RedisServer = flag.String ("redisServer", ": 6379", "")) func init () {Pool = & redis.Pool {MaxIdle: 3, / / maximum number of free links, indicating that N free links can be maintained even without redis links But not cleared MaxActive: 3, / / the maximum number of active connections, indicating the maximum number of links at the same time IdleTimeout: 240,240 * time.Second,// maximum idle link waiting time, beyond this time Idle will be turned off Dial: func () (redis.Conn, error) {c, err: = redis.Dial ("tcp", * RedisServer) if err! = nil {return nil, err} return c, err}, TestOnBorrow: func (c redis.Conn, t time.Time) error {if time.Since (t)

< time.Minute { return nil } _, err := c.Do("PING") return err }, }} 创建main.go文件实现二级缓存 package mainimport ( "database/sql" "encoding/json" "fmt" "github.com/garyburd/redigo/redis" _ "github.com/go-sql-driver/mysql" "strconv" "web/redis/redigo_pool" _ "web/redis/redigo_pool")type Person struct { Id int `db:"id"` Name string `db:"name"` Age int `db:"age"` Rmb int `db:"rmb"`}func main() { var cmd string for{ fmt.Println("输入命令") fmt.Scan(&cmd) switch cmd { case "getall": getAll() default: fmt.Println("不能识别其他命令") } fmt.Println() }}func getAll() { //从连接池当中获取链接 conn := redigo_pool.Pool.Get() //先查看redis中是否有数据 //conn,_ :=redis.Dial("tcp","localhost:6379") defer conn.Close() values, _ := redis.Values(conn.Do("lrange", "mlist",0,-1)) if len(values) >

0 {/ / if there is data fmt.Println ("get data from redis") / / get for _ directly from redis, key: = range values {pid: = string (key. ([] byte)) id, _: = strconv.Atoi (pid) results,_: = redis.Bytes (conn.Do ("GET") Id) var p Person err: = json.Unmarshal (results,&p) if err! = nil {fmt.Println ("json deserialization error")} else {fmt.Printf ("name =% s\ n") P.Name)} else {fmt.Println ("get from mysql") / / query database db,_: = sql.Open ("mysql", "root:Szt930708@tcp (localhost:3306) / mydb") defer db.Close () var persons [] Person rows,_: = db.Query ("select id,name,age") Rmb from person ") for rows.Next () {var id int var name string var age int var rmb int rows.Scan (& id,&name,&age,&rmb) per: = Person {id,name,age,rmb} persons = append (persons) Per)} / / write to redis: write person to redis as hash for _, p: = range persons {paired byteMagic _: = json.Marshal (p) _, err1: = conn.Do ("SETNX", p.Idjinger paired byte) _, err2: = conn.Do ("lpush", "mlist") P.Id) / / set the expiration time conn.Do ("EXPIRE", p.IdPower60Secret5) if err1! = nil | | err2! = nil {fmt.Println ("write failed")} else {fmt.Println ("write successful")} conn.Do ("EXPIRE") "mlist", 605th)}} that's all about how MySQL and Redis implement secondary caching. I hope the above content can be of some help to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report