# ModuleEventRegister.java

    package cloud.wconnect.workperformance.config.snsmoduleevent.initializer;

    import cloud.wconnect.sns.http.configuration.SnsHttpProperties;
    import cloud.wconnect.sns.http.processor.Register;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.event.ContextRefreshedEvent;
    import org.springframework.retry.annotation.Recover;
    import org.springframework.retry.annotation.Retryable;
    import org.springframework.stereotype.Component;
    import software.amazon.awssdk.services.sns.SnsClient;

    /**
     * 手动订阅SNS HTTPS：模块之间接收事件
     *
     * @author zc
     * @date 2023/09/12
     */
    @Component
    public class ModuleEventRegister implements ApplicationListener<ContextRefreshedEvent> {

        @Value("${w-connect.module-event.status}")
        private String status;

        @Value("${w-connect.module-event.access-key}")
        private String moduleEventAccessKey;

        @Value("${w-connect.module-event.secret-key}")
        private String moduleEventSecretKey;

        @Value("${w-connect.module-event.topic}")
        private String moduleEventTopic;

        @Value("${w-connect.module-event.endpoint}")
        private String endpoint;

        @Value("${w-connect.module-event.domain}")
        private String domain;

        @Value("${w-connect.module-event.delay}")
        private long delay;

        @Value("${w-connect.module-event.protocol}")
        private String protocol;

        @Value("${w-connect.module-event.filter-policy}")
        private String filterPolicyJson;

        private final SnsClient snsClient;

        public ModuleEventRegister(@Qualifier("moduleEventSnsClient") SnsClient snsClient) {
            this.snsClient = snsClient;
        }

        @Override
        @Retryable(value = RuntimeException.class, maxAttemptsExpression = "${w-connect.module-event.retry}")
        public void onApplicationEvent(ContextRefreshedEvent event) {   // 确保在 rest api 启动完毕后进行sns注册
            if (!"active".equals(status)) {
                return;
            }

            SnsHttpProperties properties = new SnsHttpProperties();
            properties.setAccessKey(moduleEventAccessKey);
            properties.setSecretKey(moduleEventSecretKey);
            properties.setDelay(delay);
            properties.setEndpoint(endpoint);
            properties.setDomain(domain);
            properties.setFilterPolicy(filterPolicyJson);
            properties.setProtocol(protocol);
            properties.setTopic(moduleEventTopic);

            Register register = new Register(properties, snsClient);
            register.Subscribe();
        }

        @Recover
        public void recover(RuntimeException e) {
            throw new RuntimeException("ModuleEvent SNS topic subscription failed");
        }
    }