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 used by spring to integrate redis message snooping notifications

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "what is the method used by spring to integrate redis message monitoring notification". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Problem introduction

In the e-commerce system, second kill, rush purchase, red packet coupons and other operations, generally set a time limit, such as order 15 minutes do not pay automatically closed, red packets valid for 24 hours, and so on. The simplest way to deal with this requirement is to use scheduled tasks and scan the database regularly. However, for more accurate time control, the execution time of scheduled tasks will be set very short, so it will cause a lot of database pressure.

Is there a more secure solution? We can use REDIS's key failure mechanism combined with REDIS's message notification mechanism to deal with similar problems.

1.1 description of expired issues

In e-commerce systems, time limits are generally set for operations such as second kill, rush purchase, red packet coupons, etc., such as automatic closing of orders without payment for 15 minutes, 24-hour validity of red packets, and so on.

1.2 Analysis of common solutions

At present, the most common solutions in enterprises are roughly divided into two types:

Use scheduled task processing to regularly scan expired data in the database and then modify it. However, for more accurate time control, the execution time of scheduled tasks will be set very short, so it will cause a lot of database pressure.

Message notification is used to send a message when the data fails, and the program modifies the status of the response data after receiving the failure message. This method will not put too much pressure on the database.

1.3. Integrate SpringData Redis development

We use redis to solve problems such as expired coupons and red packets, and use redis message notification in the java environment. At present, the popular AIP for java code to operate redis are: Jedis and RedisTemplate.

Jedis is a Java-oriented client officially launched by Redis, which provides many interfaces for Java language to call.

SpringData Redis is officially launched by Spring, which can be regarded as a sub-framework of Spring framework integrating Redis operations, encapsulating many commands of Redis, and it is very convenient to use Spring to operate Redis databases. Since modern enterprise development uses Spring to integrate projects, we use the SpringData Redis provided by Spring in the choice of API

Spring integrates redis snooping message 1. Configure to listen for redis messages

If we want to listen to redis's topic messages in java code, we also need to customize the listeners that handle the messages

The source code of the MessageListener class:

Package org.springframework.data.redis.connection;import org.springframework.lang.Nullable;/** * Listener of messages published in Redis. * / public interface MessageListener {/ * * Callback for processing received objects through Redis. * * @ param message message must not be {@ literal null}. * @ param pattern pattern matching the channel (if specified)-can be {@ literal null}. * / void onMessage (Message message, @ Nullable byte [] pattern);}

The code to extend this interface is as follows

/ * message listener: need to implement the MessageListener interface * implement the onMessage method * / public class RedisMessageListener implements MessageListener {/ * handle redis messages: when the message is obtained from the redis Print the topic name and basic message * / public void onMessage (Message message, byte [] pattern) {System.out.println ("from channel is" + new String (message.getChannel ()) + "got a new message with the message content:" + new String (message.getBody () }}

In this way, we define a message listener, which is processed by the onMessage method in the listener when a new message is sent to the subscribed channel.

After the listener program is written, we also need to add listeners and subscribed channel topics to the springData redis configuration file

The channel we tested for subscription is ITCAST, and the configuration is as follows:

2 Test message

After you have configured the message listener, you can start the program for testing after you have subscribed to the topic. Since there is a listener, you only need to start it in the form of java code to create a spring container (when the spring container is loaded, a listener will be created to listen to the corresponding messages all the time).

Public static void main (String [] args) {ApplicationContext ac = new ClassPathXmlApplicationContext ("applicationContext-data-redis.xml");}

When the program starts, it remains running all the time. That is, the message that subscribes to the ITCSAT channel. At this time, a message is published through the client program (redis-cli) of redis.

The command explains:

Publish topic name message content: sends a message to the specified channel

After sending the message, we take a look at the java console output to verify that the message was obtained

Deal with expired coupons by combining redis's key failure mechanism and messages.

Solving the problem of expired coupons is easier to deal with:

In redis, when a key fails, a message is also sent to the fixed channel. We only need to listen to this message to obtain the id in the database and modify the corresponding coupon status. This also brings some tedious operations: after users get the coupons, they need to save the coupons to the redis server and set the timeout.

Because you need to rely on redis's key failure notification, there are two considerations that you should pay attention to:

Events are distributed through Redis's subscription and publish function (pub/sub), so you need to subscribe to (_ _ keyevent@0__:expired) channel 0, which means db0 chooses the appropriate number according to its own dbindex.

Modify the redis.conf file

Modify notify-keyspace-events Ex

# K key space notification, prefixed with _ _ keyspace@__ # E key event notification Notification of general commands that are prefixed with _ _ keysevent@__ # g del, expipre, rename, etc. # $String command # l List command # s Set command # h Hash command # z ordered collection command # x expiration event (generated each time key expires) # e expulsion event (generated when key is full when memory is cleared) alias for # A g$lshzxe So "AKE" means that all event 1 simulates the case of expired vouchers.

Now that the pre-content has been introduced to you, we can use redis message notification combined with springDataRedis to complete the processing of an expired coupon. In order to show the problem more intuitively, here are two programs:

The first program (coupon-achieve) is used to simulate the user to get a coupon and save it to the database and store it in the redis cache.

@ RunWith (SpringJUnit4ClassRunner.class) @ ContextConfiguration (locations= "classpath:applicationContext.xml") public class CouponTest {@ Autowired private CouponMapper couponMapper; @ Autowired private RedisTemplate redisTemplate; @ Test public void testSaveCoupon () {Date now = new Date (); int timeOut = 1 / / set the expiration time of the coupon (expire after one minute) / / customize a coupon, Coupon coupon = new Coupon (); coupon.setName ("Test coupon"); / / set the name coupon.setMoney (BigDecimal.ONE) / / set amount coupon.setCouponDesc ("full category discount 10 yuan"); / / set description coupon.setCreateTime (now); / / set acquisition time / / set timeout time: timeout coupon.setExpireTime (DataUtils.addTime (now, timeOut) after 1 minute of validity of the coupon) / / setting status: 0-available 1-invalidated 2-used coupon.setState (0); couponMapper.saveCoupon (coupon) / * Save the coupon information to the redis server: * in order to facilitate processing, we only need to obtain id when processing. * so the saved key is set to coupon: the primary key of the coupon * value: set to the primary key * / redisTemplate.opsForValue (). Set ("coupon:" + coupon.getId (), coupon.getId () + ", (long) timeOut, TimeUnit.MINUTES) }

The second program (coupon-expired) configures the message to notify that the key of the listening redis is invalid, and modifies the coupon status after obtaining the notification.

Database tables:

CREATE TABLE `tcoupon` (`id` bigint (20) NOT NULL AUTO_INCREMENT COMMENT 'key', `name` varchar (60) DEFAULT NULL COMMENT 'coupon name', `money`decimal (10DEFAULT NULL COMMENT 0) DEFAULT NULL COMMENT 'amount', `create_ time`coupon description', `create_ time`coupon 'acquisition time', `expire_ time`coupon 'expiration time', `state`int (1) DEFAULT NULL COMMENT 'status, 0-valid, 1-expired 2-used' PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf82 configure key invalid messages in redis to listen for spring-data integration jedis 3 receiving invalidation messages to complete the package cn.itcast.redis.listener processing of expired vouchers Import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.connection.Message;import org.springframework.data.redis.connection.MessageListener;import cn.itcast.entity.Coupon;import cn.itcast.mapper.CouponMapper;public class RedisKeyExpiredMessageDelegate implements MessageListener {@ Autowired private CouponMapper couponMapper; public void onMessage (Message message, byte [] pattern) {/ / 1. Get the invalid key String key = new String (message.getBody ()); / / determine whether the coupon expires and notify if (key.startsWith ("coupon")) {/ / 2. Separate invalid coupons from key id String redisId = key.split (":") [1]; / / 3. Query coupon information Coupon coupon = couponMapper.selectCouponById (Long.parseLong (redisId)); / / 4. Modify the status coupon.setState (1); / / 5. Update database couponMapper.updateCoupon (coupon);}}

The test log is as follows:

Through the log, we found that when the coupon expires, redis immediately sends a message informing it that the coupon is invalid. We can get the current id in the listener and query the database modification status.

This is the end of the content of "what is the method used by spring to integrate redis message monitoring notifications". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Development

Wechat

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

12
Report