


How to efficiently store and read Go structure arrays to Redis using go-redis/redis v8?
Apr 02, 2025 pm 04:51 PM This article discusses how to efficiently store and read Go structure arrays to Redis using go-redis/redis v8
Saving the Go structure array directly to Redis will cause an error, because the SET
command of go-redis/redis v8
only supports string type key-value pairs.
The following code snippet demonstrates trying to store an array of type []model.sysrolemenu
directly to Redis and explains the cause of the error. The code is designed to get the menu tree structure and store it in Redis for quick access. After getting the getmenutree
tree data, I tried to use global.gva_redis.set
to directly store the menus
array, but because SET
method requires the value to be a string type, it failed.
The workaround is to convert the []model.sysrolemenu
array to a JSON string supported by Redis. After serializing it into a JSON string, it can be successfully stored in Redis; when reading it, it will be deserialized back to the Go structure array.
The modified getmenutree
function is as follows, converting menus
arrays to JSON strings before saving to Redis:
import ( "context" "encoding/json" "github.com/go-redis/redis/v8" "go.uber.org/zap" ) // ... other imports and code ... func GetMenuTree(roleId string) (err error, menus []model.SysRoleMenu) { err, menuTree := GetMenuTreeMap(roleId) menus = menuTree["0"] // ... other code ... jsonData, err := json.Marshal(menus) if err != nil { zap.L().Error("json marshal error", zap.Error(err)) return err, nil } err = global.gvaRedis.Set(context.Background(), "menuTree:" roleId, string(jsonData), 0).Err() if err != nil { zap.L().Error("redis set error", zap.Error(err)) return err, nil } return nil, menus } //A sample to read data func ReadMenuTree(roleId string) (err error, menus []model.SysRoleMenu) { val, err := global.gvaRedis.Get(context.Background(), "menuTree:" roleId).Result() if err != nil { if err == redis.Nil { return nil, nil //Key does not exist} return err, nil } err = json.Unmarshal([]byte(val), &menus) if err != nil { zap.L().Error("json unmarshal error", zap.Error(err)) return err, nil } return nil, menus }
Encode menus
array into a JSON string through the json.Marshal
function and store it in Redis. When reading data, use json.Unmarshal
for deserialization. This solves the problem that go-redis/redis v8
does not support direct storage of array structures.
The above is the detailed content of How to efficiently store and read Go structure arrays to Redis using go-redis/redis v8?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

With the vigorous development of the Internet, Korean comics (Korean comics) have won the love of more and more readers around the world with their exquisite painting style, fascinating plots and rich and diverse themes. If you want to travel anywhere, in the exciting Korean comic world, it is crucial to find a stable, free and resource-rich online reading platform. This article will provide you with a detailed guide to watching Korean comics online for free comics, helping you easily start your Korean comic journey.

To log in to AO3, first access the available mirrored sites, and then follow the steps: 1. Select the mirrored site and enter the URL; 2. Click the "Log In" button in the upper right corner of the homepage or in the navigation bar; 3. Enter the user name and password; 4. Select "Remember me" to automatically log in next time (but do not select public computers); 5. After confirming that the information is correct, click "Log In" to complete the login. If you encounter problems, you can check the network connection, confirm the correctness of the username and password, clear the browser cache and cookies, change the mirrored site, and try to use the Tor browser. In the end, you can contact AO3 customer service if it still cannot be resolved. In addition, when using AO3, you must respect the author's copyright and pay attention to content grading

Global cryptocurrency exchange Kucoin recently completed the formation of its European leadership team, appointing two highly-watched executives. This personnel change is part of Kucoin’s accelerated layout in the EU market, especially in response to the upcoming cryptoasset management regulations (MICAR). Currently, the company is advancing the relevant licensing process through the Austrian Financial Markets Authority (FMA) and introducing senior experts from traditional finance and crypto to strengthen its management. KucoinEU is currently actively communicating with the FMA to achieve full compliance operations with the goal of providing a complete cryptocurrency service within the European Economic Area (EEA). At this stage, the company has not yet conducted business within the EU or EEA and is about to obtain the corresponding license.

Short-term crypto trading is risky, but it is one of the most favorable ways to make money. If you know how to apply the right strategy, the most important thing is to choose the right crypto assets, you can make a considerable profit, which is exactly what we are going to discuss today. Which currencies can make investors profit in the short term? How to choose? Recommended short-term profitable currencies in the currency circle How to choose short-term trading cryptocurrencies? Short-term transactions involve buying cryptocurrencies and holding them for a short period of time, ranging from minutes to days. This approach is both promising, risky and time-consuming as you need to constantly monitor the market. But that's not all; when choosing the right crypto assets, you should also pay attention to the following points:

Stablecoin, as a key bridge connecting the traditional finance and crypto world, continues to play an important role in 2025. From the initial USDT and USDC to emerging algorithmic stablecoins and synthetic assets, various stablecoins have been continuously evolving in terms of stability, compliance and composability. So, what are the latest stablecoins in 2025? How are they different in technology and application scenarios? This article will give you a comprehensive understanding.

TopullupdatesfromaGitsubtree,youmustexplicitlymergechangesfromtheremoterepositoryusingspecificsteps.1.Addthesubtreeremoteifnotalreadyaddedwithgitremoteadd-f.2.Mergethelatestchangesusinggitmerge--srecursive--no-commit/.3.Applythechangestothecorrectsub

To keep the fork synchronized with the original (upstream) repository, follow the following steps: 1. Add the upstream remote repository, run gitremoteaddupstream https://github.com/original-owner/repo-name.git; 2. Get the latest upstream changes, run gitfetchupstream; 3. Switch to the local branch and merge the updates, run gitcheckoutmain and gitmergeupstream/main in turn. If there are any conflicts, you need to resolve them manually; Optional steps: Push the updated branch to your fork and run gitpushoriginmain. also

To find the official online portal of Ouyi, please check the SSL certificate, obtain links through official social media or partners, and avoid clicking on ads or links sent by strangers; when downloading the Android version of the app, you need to download it through the official website and follow the steps; when encountering installation problems, you can check the network, storage space, system version, etc.; when using the app, you should set a strong password, turn on 2FA, protect the private key, and be wary of phishing information. 1. Confirm the security of the domain name and SSL certificate when accessing the official website; 2. Pay attention to the latest links published by the official channel; 3. Do not click on the ad link at will through search engines; 4. Ensure that the source is reliable and allow installation from unknown sources when downloading Android; 5. If the installation fails, try to clear the cache or restart the phone; 6. In terms of account security, complex passwords must be set and dual-enabled
