Two lines of code implement Redis message queue, simple and easy to use

The Redis list data type is very suitable for use as a message queue. Insert new messages at the end of the list, and then remove messages from the head of the list for processing. This solution is simple and easy to use, and supports multiple consumers to process messages in parallel.

The message queue can be implemented with two lines of core code, as follows:

// 推送消息
redisTemplate.opsForList().leftPush(queueName, message);
// 接收消息
redisTemplate.opsForList().rightPop(queueName);

To implement a message queue, the specific steps are as follows:

Configure Redis connection information

In a Spring Boot application, you can use application.properties or application.yml files to configure Redis connection information. An example configuration is as follows:

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=yourpassword

Create RedisTemplate bean

Create a RedisTemplate bean to perform Redis operations in subsequent code. The sample code is as follows:

@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<String, String> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new StringRedisSerializer());
    return template;
}

Implement message queue logic

Use the opsForList() method of RedisTemplate to obtain the ListOperations object, then use the leftPush() method to insert the message into the head of the list, and use the rightPop() method to remove the message from the end of the list for processing. The sample code is as follows:

@Autowired
private RedisTemplate<String, String> redisTemplate;

public void sendMessage(String queueName, String message) {
    redisTemplate.opsForList().leftPush(queueName, message);
}

public String receiveMessage(String queueName) {
    return redisTemplate.opsForList().rightPop(queueName);
}

Write a message queue usage example

Examples are as follows:

@RestController
public class MessageController {

    @Autowired
    private RedisMessageQueue redisMessageQueue;

    @RequestMapping("/send")
    public String sendMessage(@RequestParam(value = "message") String message) {
        String queueName = "message-queue";
        redisMessageQueue.sendMessage(queueName, message);
        return "Message sent: " + message;
    }

    @RequestMapping("/receive")
    public String receiveMessage() {
        String queueName = "message-queue";
        String message = redisMessageQueue.receiveMessage(queueName);
        return "Message received: " + message;
    }
}

Test message sent:

curl http://localhost:8080/send?message=hello

Test message reception:

curl http://localhost:8080/receive
// 返回 Message received: hello

Defects of Redis message queue

Redis message queue is a lightweight message queue implemented based on Redis. It has the advantages of efficiency, reliability, flexibility, etc., but it also has the following defects:

  1. Availability issues: When the Redis node goes down or the network fails, messages may be lost. To avoid this situation, master-slave replication or cluster mode needs to be used to improve availability.
  2. Queue length issue: Since Redis is an in-memory database, you need to pay attention to the impact of queue length on system resources when processing a large number of messages. If the queue length is too long, it may cause the Redis node to crash or slow down the execution efficiency.
  3. Message persistence issue: By default, the Redis message queue does not support message persistence. If you need to implement message persistence, you need to manually write the message to disk or use Redis RDB and AOF files for persistence operations.
  4. Message order problem: Redis message queue does not guarantee the order of messages. If you need to ensure the order of messages, you need to set up multiple queues or use other methods to achieve this.

Related content expansion: (Technology Frontier)

In the past 10 years, when even traditional enterprises began to digitize on a large scale, we found that in the process of developing internal tools, a large number of pages, scenes, components, etc. were constantly repeated. This repetitive work of reinventing the wheel wasted a lot of engineers' time.

To address this type of problem, low-code concretizes certain recurring scenes and processes into components, APIs, and database interfaces to avoid reinventing the wheel. Greatly improves programmers' productivity.

Recommend a software JNPF rapid development platform that all programmers should know. It adopts the industry-leading SpringBoot microservice architecture and supports SpringCloud mode, which improves the platform's expansion foundation and meets the needs of rapid system development, flexible expansion, seamless integration and high-end Comprehensive capabilities such as performance applications; using the front-end and back-end separation model, front-end and back-end developers can work together to take charge of different sectors, which is trouble-free and convenient.

Experience the official website: https://www.jnpfsoft.com/?csdn

If you haven’t learned about low-code technology yet, you can quickly experience it and learn it!

Guess you like

Origin blog.csdn.net/Z__7Gk/article/details/132833659