国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Usage Scenarios
1. Introduce Redisson dependency
2. Nacos configuration Redis connection
3. Create RedissonConfig configuration
4. Encapsulate Redis delay queue tool class
5. Create a delay queue business enumeration
6. Define the delay queue executor
7. Create the Bean, defined in the enumeration and implement the delay queue executor
8. Create a delay queue consumption thread,Start after the project is started
9. Create a test interface,Simulation Add a delay queue
10. Start the SpringBoot project,Use the PostMan calling interface to add a delay queue
Home Java javaTutorial How SpringBoot integrates Redisson to implement delay queue

How SpringBoot integrates Redisson to implement delay queue

May 30, 2023 pm 02:40 PM
springboot redisson

Usage Scenarios

1. The order was successfully placed but not paid for 30 minutes. Payment timeout,Automatic cancellation of order

2. Order receipt,No evaluation will be conducted within 7 days after receipt. The order timed out and was not evaluated,The system defaults to a positive review

3. The order was placed successfully,The merchant did not receive the order within 5 minutes,The order was cancelled

4.The delivery timed out xff0c;Push SMS reminder

……

For scenarios with long delays and low real-time performance, we can use task scheduling to process polling at regular intervals. For example,:xxl-job

Today we adopt a relatively simple and lightweight method-using Redis' delay queue for processing. Of course there are better solutions - you can choose the optimal solution based on the company's technology selection and business system. For example, use the message middleware Kafka and RabbitMQ's delay queue

Let's not discuss its implementation principle. Let's go directly to the actual code and first implement the Redis-based delay queue

1. Introduce Redisson dependency

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.10.5</version>
</dependency>

2. Nacos configuration Redis connection

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: 123456
    database: 12
    timeout: 3000

3. Create RedissonConfig configuration

/**
 * Created by LPB on 2020/04/20.
 */
@Configuration
public class RedissonConfig {

	@Value("${spring.redis.host}")
	private String host;
	@Value("${spring.redis.port}")
	private int port;
	@Value("${spring.redis.database}")
	private int database;
	@Value("${spring.redis.password}")
	private String password;

	@Bean
	public RedissonClient redissonClient() {
		Config config = new Config();
		config.useSingleServer()
			.setAddress("redis://" + host + ":" + port)
			.setDatabase(database)
			.setPassword(password);
		return Redisson.create(config);
	}

}

4. Encapsulate Redis delay queue tool class

/**
 * redis延遲隊(duì)列工具
 * Created by LPB on 2021/04/20.
 */
@Slf4j
@Component
public class RedisDelayQueueUtil {

    @Autowired
	private RedissonClient redissonClient;

    /**
     * 添加延遲隊(duì)列
     * @param value 隊(duì)列值
     * @param delay 延遲時(shí)間
     * @param timeUnit 時(shí)間單位
     * @param queueCode 隊(duì)列鍵
     * @param <T>
     */
    public <T> void addDelayQueue(T value, long delay, TimeUnit timeUnit, String queueCode){
        try {
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueCode);
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            delayedQueue.offer(value, delay, timeUnit);
			log.info("(添加延時(shí)隊(duì)列成功) 隊(duì)列鍵&#xff1a;{}&#xff0c;隊(duì)列值&#xff1a;{}&#xff0c;延遲時(shí)間&#xff1a;{}", queueCode, value, timeUnit.toSeconds(delay) + "秒");
        } catch (Exception e) {
            log.error("(添加延時(shí)隊(duì)列失敗) {}", e.getMessage());
            throw new RuntimeException("(添加延時(shí)隊(duì)列失敗)");
        }
    }

	/**
	 * 獲取延遲隊(duì)列
	 * @param queueCode
	 * @param <T>
	 * @return
	 * @throws InterruptedException
	 */
    public <T> T getDelayQueue(String queueCode) throws InterruptedException {
        RBlockingDeque<Map> blockingDeque = redissonClient.getBlockingDeque(queueCode);
        T value  = (T) blockingDeque.take();
        return value;
	}
}

5. Create a delay queue business enumeration

/**
 * 延遲隊(duì)列業(yè)務(wù)枚舉
 * Created by LPB on 2021/04/20.
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum RedisDelayQueueEnum {

	ORDER_PAYMENT_TIMEOUT("ORDER_PAYMENT_TIMEOUT","訂單支付超時(shí)&#xff0c;自動(dòng)取消訂單", "orderPaymentTimeout"),
	ORDER_TIMEOUT_NOT_EVALUATED("ORDER_TIMEOUT_NOT_EVALUATED", "訂單超時(shí)未評(píng)價(jià)&#xff0c;系統(tǒng)默認(rèn)好評(píng)", "orderTimeoutNotEvaluated");

	/**
	 * 延遲隊(duì)列 Redis Key
	 */
	private String code;

	/**
	 * 中文描述
	 */
	private String name;

	/**
	 * 延遲隊(duì)列具體業(yè)務(wù)實(shí)現(xiàn)的 Bean
	 * 可通過(guò) Spring 的上下文獲取
	 */
	private String beanId;

}

6. Define the delay queue executor

/**
 * 延遲隊(duì)列執(zhí)行器
 * Created by LPB on 2021/04/20.
 */
public interface RedisDelayQueueHandle<T> {

	void execute(T t);

}

7. Create the Bean, defined in the enumeration and implement the delay queue executor

  • OrderPaymentTimeout:Order payment timeout delay queue processing class

/**
 * 訂單支付超時(shí)處理類(lèi)
 * Created by LPB on 2021/04/20.
 */
@Component
@Slf4j
public class OrderPaymentTimeout implements RedisDelayQueueHandle<Map> {
	@Override
	public void execute(Map map) {
		log.info("(收到訂單支付超時(shí)延遲消息) {}", map);
		// TODO 訂單支付超時(shí)&#xff0c;自動(dòng)取消訂單處理業(yè)務(wù)...

	}
}
  • DelayQueueProcessorForUnevaluatedOrders: Delay queue processing class for processing unevaluated orders , used when the order times out and is not evaluated

/**
 * 訂單超時(shí)未評(píng)價(jià)處理類(lèi)
 * Created by LPB on 2021/04/20.
 */
@Component
@Slf4j
public class OrderTimeoutNotEvaluated implements RedisDelayQueueHandle<Map> {
	@Override
	public void execute(Map map) {
		log.info("(收到訂單超時(shí)未評(píng)價(jià)延遲消息) {}", map);
		// TODO 訂單超時(shí)未評(píng)價(jià)&#xff0c;系統(tǒng)默認(rèn)好評(píng)處理業(yè)務(wù)...

	}
}

8. Create a delay queue consumption thread,Start after the project is started

/**
 * 啟動(dòng)延遲隊(duì)列
 * Created by LPB on 2021/04/20.
 */
@Slf4j
@Component
public class RedisDelayQueueRunner implements CommandLineRunner {

	@Autowired
	private RedisDelayQueueUtil redisDelayQueueUtil;

	@Override
	public void run(String... args) {
		new Thread(() -> {
			while (true){
				try {
					RedisDelayQueueEnum[] queueEnums = RedisDelayQueueEnum.values();
					for (RedisDelayQueueEnum queueEnum : queueEnums) {
						Object value = redisDelayQueueUtil.getDelayQueue(queueEnum.getCode());
						if (value != null) {
							RedisDelayQueueHandle redisDelayQueueHandle = SpringUtil.getBean(queueEnum.getBeanId());
							redisDelayQueueHandle.execute(value);
						}
					}
				} catch (InterruptedException e) {
					log.error("(Redis延遲隊(duì)列異常中斷) {}", e.getMessage());
				}
			}
		}).start();
		log.info("(Redis延遲隊(duì)列啟動(dòng)成功)");
	}
}

The above steps ,Redis delay queue core code has been completed,Let’s write a test interface,Use PostMan to simulate and test it

9. Create a test interface,Simulation Add a delay queue

/**
 * 延遲隊(duì)列測(cè)試
 * Created by LPB on 2020/04/20.
 */
@RestController
public class RedisDelayQueueController {

	@Autowired
	private RedisDelayQueueUtil redisDelayQueueUtil;

	@PostMapping("/addQueue")
	public void addQueue() {
		Map<String, String> map1 = new HashMap<>();
		map1.put("orderId", "100");
		map1.put("remark", "訂單支付超時(shí)&#xff0c;自動(dòng)取消訂單");

		Map<String, String> map2 = new HashMap<>();
		map2.put("orderId", "200");
		map2.put("remark", "訂單超時(shí)未評(píng)價(jià)&#xff0c;系統(tǒng)默認(rèn)好評(píng)");

		// 添加訂單支付超時(shí)&#xff0c;自動(dòng)取消訂單延遲隊(duì)列。為了測(cè)試效果&#xff0c;延遲10秒鐘
		redisDelayQueueUtil.addDelayQueue(map1, 10, TimeUnit.SECONDS, RedisDelayQueueEnum.ORDER_PAYMENT_TIMEOUT.getCode());

		// 訂單超時(shí)未評(píng)價(jià)&#xff0c;系統(tǒng)默認(rèn)好評(píng)。為了測(cè)試效果&#xff0c;延遲20秒鐘
		redisDelayQueueUtil.addDelayQueue(map2, 20, TimeUnit.SECONDS, RedisDelayQueueEnum.ORDER_TIMEOUT_NOT_EVALUATED.getCode());
	}

}

10. Start the SpringBoot project,Use the PostMan calling interface to add a delay queue

  • You can see through the Redis client that the two delay queues have been Added successfully

How SpringBoot integrates Redisson to implement delay queue

  • Check the IDEA console log to see that the delay queue has been consumed successfully

How SpringBoot integrates Redisson to implement delay queue

The above is the detailed content of How SpringBoot integrates Redisson to implement delay queue. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 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)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

The king solution among distributed locks - Redisson The king solution among distributed locks - Redisson Aug 24, 2023 pm 03:31 PM

If you have been using Redis before, you will get twice the result with half the effort by using Redisson. Redisson provides the simplest and most convenient way to use Redis. The purpose of Redisson is to promote users' separation of concerns (Separation of Concern) from Redis, so that users can focus more on processing business logic.

See all articles