StartUpAndShutdown.java 1.53 KB
package com.objecteye.handle;

import com.objecteye.content.ViidCollectorRedisKey;
import com.objecteye.handle.viid.CommonHandle;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.function.Consumer;

/**
 * @author: liuhaoyu
 * @date: 2023/6/30
 */
@Component
@RequiredArgsConstructor
public class StartUpAndShutdown implements DisposableBean, ApplicationRunner {
    private final CommonHandle commonHandle;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public void destroy() throws Exception {
        allCacheHandle(commonHandle::unregister);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        allCacheHandle(commonHandle::register);
    }

    private void allCacheHandle(Consumer<String> func) {
        try (Cursor<Map.Entry<Object, Object>> cursor = stringRedisTemplate.boundHashOps(ViidCollectorRedisKey.DEVICE_CACHE)
                .scan(ScanOptions.scanOptions().build())) {
            while (cursor.hasNext()) {
                Map.Entry<Object, Object> entry = cursor.next();
                func.accept(entry.getKey().toString());
            }
        }
    }
}