Eureka 整理

  服务治理:(该模块也可以使用集群)

  该模块主要负责完成微服务架构中的服务治理功能。

  1.构建服务注册中心。 每个服务单元需要向注册中心登记自己提供的服务。

  2.服务注册与服务发现。 服务之间的调用不再通过制定具体的实例地址进行,而是通过向服务名发起请求调用实现。所以,服务在调用的时候,并不知道具体的地址。

  3.Eureka  的基础构架。

  4.Eureka 的服务治理机制。

  5.Eureka 的配置。

  

  服务提供者(给服务注册中心提供服务),服务消费者(调用服务注册中心的服务)。

  该服务客户端将默认每隔30s向注册中心发送心跳检测,如果没有接受到心跳检测,就会将服务进行关闭。

  出现红色部分,是eureka的自我保护机制。

  @EnableDiscoveryClient   // 声明这是eureka的客户端,这个和@EnableEurekaClient的区别是,它可以使用其他注册中心


 

// 配置
#是否注册到服务中心去
eureka.client.register-with-eureka=true
#是否从服务中心获取值
eureka.client.fetch-registry=false
#用服务注册中心的地址相同(指定客户端和服务端通讯的地址)
eureka.client.service-url.defaultZone=http://localhost:8901/eureka/
#是否把自己的ip地址注册到服务中心去
eureka.instance.ip-address=true
 

 一个项目调用另外一个项目的实例:

package ch.order.service;

import ch.order.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Description:
 *
 * @author cy
 * @date 2018年11月21日 9:43
 * version 1.0
 */
@Service
public class GoodsService {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    /**
     * 根据id进行查询
     * @param id
     * @return
     */
    public Goods queryGoodsById(String id){
        String serviceId = "my-goods";
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        if(instances.isEmpty() || instances == null){
            return null;
        }
        ServiceInstance serviceInstance = instances.get(0);
        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort();
        Goods forEntity = restTemplate.getForObject(url+"/goods/"+id, Goods.class);
        return forEntity;
    }
}

  

原文地址:https://www.cnblogs.com/chengyangyang/p/9927254.html