spring boot combined with redis monitoring to realize message timeout processing

Posted by plisken on Tue, 22 Oct 2019 18:32:33 +0200

**The project has a function to monitor whether a service is online. * *
*The service will send "heartbeat" to the back-end every 5 seconds (the heartbeat can be a string, a value, etc.). Once the service fails to send "heartbeat" to the back-end for more than 30 seconds, the back-end processing judges that the service is offline. *

Talk less nonsense, go straight to the code.

Interface (used to receive the heartbeat transmitted from the front end)

package com.yingxiao.microservice.gongdan.controller;

import com.yingxiao.microservice.gongdan.entity.Sensor;
import com.yingxiao.microservice.gongdan.model.ApiResult;
import com.yingxiao.microservice.gongdan.service.impl.SensorServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Auther : xiaobao
 * @Date : 2019/7/18 11:08
 * @Description :
 */
@Api(tags = "ID card sensor heartbeat verification interface")
@RestController
@RequestMapping(value = "sensor/beat")
public class SensorBeatController {

    private Logger logger = LoggerFactory.getLogger(getClass().getName());

    @Resource
    SensorServiceImpl sensorService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ApiOperation(value = "Verification method",notes = "The heartbeat is accepted every 5 seconds. If it is not accepted for more than 30 seconds, the sensor is offline.")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beat",value = "Character string",required = true,paramType = "query")
    })
    @PostMapping(value = "accept")
    public ApiResult SensorBeat(String beat){
        //First accept deposit current time
        //Remove <>30
        //Judge whether the string is empty
        if (beat != null && beat != ""){
            //Determine whether the string is hello
            if ("hello".equals(beat)){
                redisTemplate.opsForValue().set("beat",beat,30, TimeUnit.SECONDS);
                Sensor sensor = new Sensor();
                sensor.setName("ID card sensor");
                sensor.setStatus("1");
                sensor.setSysTime(new Date());
                sensorService.insert(sensor);
            }
        }
        return new ApiResult(200,"already accept");
    }
}


redis listener profile

package com.yingxiao.microservice.gongdan.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * @Auther : xiaobao
 * @Date : 2019/7/18 15:01
 * @Description : redis Listener profile
 */
@Configuration
public class RedisListenerConfig {

    @Bean
    @Primary
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //The following is a flexible configuration, which deals with the invalid key s of each library.
        //container.addMessageListener(new RedisExpiredListener(), new PatternTopic("__keyevent@0__:expired"));
        return container;
    }
}

Defining listeners

package com.yingxiao.microservice.gongdan.constant;

import com.yingxiao.microservice.gongdan.entity.Sensor;
import com.yingxiao.microservice.gongdan.service.impl.SensorServiceImpl;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Auther : xiaobao
 * @Date : 2019/7/18 15:09
 * @Description : redis Monitor
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Resource
    SensorServiceImpl sensorService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * Data processing is conducted for the redis data failure event.
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // Users can do their own business processing. Note that message.toString() can get the invalid key.
        String expiredKey = message.toString();
        if(expiredKey.startsWith("beat")){
            System.out.println("ID card sensor offline");
            Sensor sensor = new Sensor();
            sensor.setSysTime(new Date());
            sensor.setStatus("0");
            sensor.setName("ID card sensor");
            sensorService.insert(sensor);
        }
    }
}

Entity class. The interface between Service and Mapper is not written. Combined with the database, the state of a Service is persisted in the database. We have to say that the redis database is very powerful. You can subscribe, capture, monitor, learn and get new skills together.

Topics: Mobile Redis Java Database less