码迷,mamicode.com
首页 > 其他好文 > 详细

Eureka注册中心添加IP限制

时间:2020-06-20 17:00:40      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:org   实例   本地   source   imp   默认值   factor   empty   gets   

注册中心需要限制固定的IP才能进行注册,通过下面的操作可以实现:

import java.util.List;

import com.netflix.eureka.lease.Lease;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRegisteredEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRenewedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.Application;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl;
import com.netflix.eureka.resources.ServerCodecs;
import org.springframework.context.ApplicationEvent;
import org.springframework.util.CollectionUtils;


public class CustomInstanceRegistry extends PeerAwareInstanceRegistryImpl
        implements ApplicationContextAware {

    private ApplicationContext ctxt;
    private int defaultOpenForTrafficCount;

    private List<String> allowedRegisteredIpAddress;

    Logger log = LoggerFactory.getLogger(CustomInstanceRegistry.class);

    public CustomInstanceRegistry(EurekaServerConfig serverConfig,
                                  EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
                                  EurekaClient eurekaClient, int expectedNumberOfRenewsPerMin,
                                  int defaultOpenForTrafficCount,
                                  List<String> allowedRegisteredIpAddress) {
        super(serverConfig, clientConfig, serverCodecs, eurekaClient);

        this.expectedNumberOfRenewsPerMin = expectedNumberOfRenewsPerMin;
        this.defaultOpenForTrafficCount = defaultOpenForTrafficCount;
        this.allowedRegisteredIpAddress = allowedRegisteredIpAddress;
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.ctxt = context;
    }

    @Override
    public void openForTraffic(ApplicationInfoManager applicationInfoManager, int count) {
        super.openForTraffic(applicationInfoManager,
                count == 0 ? this.defaultOpenForTrafficCount : count);

    }

    @Override
    public void register(InstanceInfo info, int leaseDuration, boolean isReplication) {
        handleRegistration(info, leaseDuration, isReplication);
        //不允许注册的IP地址
        if (!CollectionUtils.isEmpty(allowedRegisteredIpAddress) &&
                !allowedRegisteredIpAddress.contains(info.getIPAddr())) {
            log.warn("IP 地址被禁止注册到Eureka实例中:{}", info.getIPAddr());
            return;
        }
        super.register(info, leaseDuration, isReplication);
    }

    @Override
    public void register(final InstanceInfo info, final boolean isReplication) {
        handleRegistration(info, resolveInstanceLeaseDuration(info), isReplication);
        //不允许注册的IP地址
        if (!CollectionUtils.isEmpty(allowedRegisteredIpAddress) &&
                !allowedRegisteredIpAddress.contains(info.getIPAddr())) {
            log.warn("IP 地址被禁止注册到Eureka实例中:{}", info.getIPAddr());
            return;
        }
        super.register(info, isReplication);
    }

    @Override
    public boolean cancel(String appName, String serverId, boolean isReplication) {
        handleCancelation(appName, serverId, isReplication);
        return super.cancel(appName, serverId, isReplication);
    }

    @Override
    public boolean renew(final String appName, final String serverId,
                         boolean isReplication) {
        log("renew " + appName + " serverId " + serverId + ", isReplication {}"
                + isReplication);
        List<Application> applications = getSortedApplications();
        for (Application input : applications) {
            if (input.getName().equals(appName)) {
                InstanceInfo instance = null;
                for (InstanceInfo info : input.getInstances()) {
                    if (info.getId().equals(serverId)) {
                        instance = info;
                        break;
                    }
                }
                publishEvent(new EurekaInstanceRenewedEvent(this, appName, serverId,
                        instance, isReplication));
                break;
            }
        }
        return super.renew(appName, serverId, isReplication);
    }

    @Override
    protected boolean internalCancel(String appName, String id, boolean isReplication) {
        handleCancelation(appName, id, isReplication);
        return super.internalCancel(appName, id, isReplication);
    }

    private void handleCancelation(String appName, String id, boolean isReplication) {
        log("cancel " + appName + ", serverId " + id + ", isReplication " + isReplication);
        publishEvent(new EurekaInstanceCanceledEvent(this, appName, id, isReplication));
    }

    private void handleRegistration(InstanceInfo info, int leaseDuration,
                                    boolean isReplication) {
        log("register " + info.getAppName() + ", vip " + info.getVIPAddress()
                + ", leaseDuration " + leaseDuration + ", isReplication "
                + isReplication);
        publishEvent(new EurekaInstanceRegisteredEvent(this, info, leaseDuration,
                isReplication));
    }

    private void log(String message) {
        if (log.isDebugEnabled()) {
            log.debug(message);
        }
    }

    private void publishEvent(ApplicationEvent applicationEvent) {
        this.ctxt.publishEvent(applicationEvent);
    }

    private int resolveInstanceLeaseDuration(final InstanceInfo info) {
        int leaseDuration = Lease.DEFAULT_DURATION_IN_SECS;
        if (info.getLeaseInfo() != null && info.getLeaseInfo().getDurationInSecs() > 0) {
            leaseDuration = info.getLeaseInfo().getDurationInSecs();
        }
        return leaseDuration;
    }
}
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.resources.ServerCodecs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.Arrays;

@Configuration
public class RegisterConfig {

    @Autowired
    private EurekaServerConfig eurekaServerConfig;
    @Autowired
    private EurekaClientConfig eurekaClientConfig;
    @Autowired
    @Qualifier(value = "eurekaClient")
    private EurekaClient eurekaClient;

    @Value("${eureka.server.expectedNumberOfRenewsPerMin:1}")
    private int expectedNumberOfRenewsPerMin;

    @Value("${eureka.server.defaultOpenForTrafficCount:1}")
    private int defaultOpenForTrafficCount;

    @Value("${eureka.server.allowed.address:‘‘}")
    private String[] allowedAddress;

    @Primary
    @Bean(name = "mypeerAwareInstanceRegistry")
    public PeerAwareInstanceRegistry peerAwareInstanceRegistry(
            ServerCodecs serverCodecs) {
        this.eurekaClient.getApplications();
        return new CustomInstanceRegistry(
                this.eurekaServerConfig,
                this.eurekaClientConfig,
                serverCodecs,
                this.eurekaClient,
                this.expectedNumberOfRenewsPerMin,
                this.defaultOpenForTrafficCount,
                Arrays.asList(allowedAddress)
        );
    }
}
@Value("${eureka.server.defaultOpenForTrafficCount:1}")
后面的 :1 表示${eureka.server.defaultOpenForTrafficCount}如果取值为空,则默认值为1
@Value("${eureka.server.allowed.address:‘‘}")
后面的 :‘‘ 表示${eureka.server.allowed.address}如果取值为空,则默认值为‘‘
技术图片
只允许192.168.1.141注册到该注册中心中
看下我本地的IP
技术图片

 然后我启动一个服务,注册到该注册中心中

Eureka客户端日志

技术图片

 Eureka注册中心日志:

技术图片

 说明配置成功,如果先要配置多个IP,只需用

eureka.server.allowed.address的值使用逗号隔开就行,例如:192.168.1.141,192.168.1.140

Eureka注册中心添加IP限制

标签:org   实例   本地   source   imp   默认值   factor   empty   gets   

原文地址:https://www.cnblogs.com/java-spring/p/13168872.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!