


How to solve the problem of data type conversion when using Redis's Stream to implement message queues in Go language?
Go Redis Stream Message Queue: Cleverly Solve Data Type Conversion Problem
When building message queues using Go and Redis Stream, you often encounter data type conversion problems. This article will explore this issue in depth and provide effective solutions.
Problem description
Suppose you build a message queue system based on Redis Stream. You may encounter the following situations:
-
Write data: You write data to Redis Stream where
user_id
field is an integer type (int
).// Example of writing data client.XAdd(ctx, &redis.XAddArgs{ Stream: "mystream", Values: map[string]interface{}{ "user_id": 123, "message": "hello, world!", }, })
Copy after login -
Read data: However, when you read data, the
user_id
field becomes a string type (string
).// Example of reading data entries, err := client.XRead(ctx, &redis.XReadArgs{ Streams: []string{"mystream", "0"}, }) if err != nil { panic(err) } for _, msg := range entries[0].Messages { fmt.Printf("user_id type: %T, value: %v\n", msg.Values["user_id"], msg.Values["user_id"]) }
Copy after login
This results in a type mismatch and requires additional processing. Why does this happen? Do we need to manually convert the type every time we read it?
Root Cause Analysis and Solutions
Redis underlying storage data usually exists in string form, even if you write a numeric type. Redis Stream is no exception.
To solve this problem, the following strategies are recommended:
-
Structure serialization and deserialization: Before writing to Redis, serialize the data structure into a JSON string; deserialize it back to the Go structure when reading.
// Define the message structure type Message struct { UserID int `json:"user_id"` Message string `json:"message"` } // Write data msg := Message{UserID: 123, Message: "Hello, World!"} data, err := json.Marshal(msg) if err != nil { panic(err) } client.XAdd(ctx, &redis.XAddArgs{ Stream: "mystream", Values: map[string]interface{}{ "data": string(data), }, }) // Read data entries, err := client.XRead(ctx, &redis.XReadArgs{ Streams: []string{"mystream", "0"}, }) if err != nil { panic(err) } for _, msg := range entries[0].Messages { var receivedMsg Message json.Unmarshal([]byte(msg.Values["data"].(string)), &receivedMsg) fmt.Printf("user_id: %d, message: %s\n", receivedMsg.UserID, receivedMsg.Message) }
Copy after loginBy serializing and deserializing, ensure that the data types are consistent between Redis and Go programs, avoiding the hassle of type conversion.
Using this method can effectively avoid data type conversion problems and improve the readability and maintainability of the code. Remember to always handle potential errors such as JSON codec errors.
The above is the detailed content of How to solve the problem of data type conversion when using Redis's Stream to implement message queues in Go language?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

JDBC...

Understand the randomness of circular dependencies in Spring project startup. When developing Spring project, you may encounter randomness caused by circular dependencies at project startup...

The optimization solution for SpringBoot timing tasks in a multi-node environment is developing Spring...

Why is the return value empty when using RedisTemplate for batch query? When using RedisTemplate for batch query operations, you may encounter the returned results...

Factors of rising virtual currency prices include: 1. Increased market demand, 2. Decreased supply, 3. Stimulated positive news, 4. Optimistic market sentiment, 5. Macroeconomic environment; Decline factors include: 1. Decreased market demand, 2. Increased supply, 3. Strike of negative news, 4. Pessimistic market sentiment, 5. Macroeconomic environment.

Discussion on the reasons why JavaScript cannot obtain user computer hardware information In daily programming, many developers will be curious about why JavaScript cannot be directly obtained...
