SpringCloud 之Eureka

100 阅读2分钟

这是我参与8月更文挑战的第7天,活动详情查看:8月更文挑战

Eureka是Netflix开发的一个服务发现框架,已集成到spring cloud Netflix中,负责服务注册与发现。

Eureka中分为eureka server和eureka client。其中eureka server是作为服务的注册与发现中心。eureka client既可以作为服务的生产者,又可以作为服务的消费者。

注册中心原理:

  1. 注册中心启动
  2. 服务生成者启动注册到服务中心
  3. 服务消费者从注册中心获取服务信息
  4. 服务消费者远程调用服务提供者

使用

1.创建Server

创建一个module,添加web和eureka依赖

启动类添加注解
@SpringBootApplication
@EnableEurekaServer
public class ServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServerApplication.class, args);
    }
}

配置yml文件
#port
server:
  port: 8761

#appliction
spring:
  application:
    name: eureka-server

#eureka
eureka:
  #实例名默认localhost
  instance:
    hostname: eureka_server
  client:
    #是否将自己注册到注册中心,默认true
    register-with-eureka: false
    #是否从server获取注册的服务信息
    fetch-registry: false
  server:
    #自我保护机制默认true,心跳失败比例在15分钟低于85%就不剔除client
    enable-self-preservation: true
    #保护机制的阈值,默认是0.85
    renewal-percent-threshold: 0.85
    #清理无效节点时间间隔,默认60秒
    eviction-interval-timer-in-ms: 60000
    #Eureka服务器获取不到集群里对等服务器上的实例时,需要等待的时间,单位为毫秒
    wait-time-in-ms-when-sync-empty: 0

2.创建client

因为client既可以做服务生产者,也可以做服务消费者,所以创建2个client测试。

添加注解

使用***@EnableEurekaClient*** 或***@EnableDiscoveryClient***

@SpringBootApplication
@EnableDiscoveryClient
public class ClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(ClientApplication.class, args);
    }
}
配置yml
#port
server:
  port: 8801

#application
#注册的名字.跟服务端其实是一样的。如果想要一个服务多节点,节点的名字是要一样
spring:
  application:
    name: client1

#eureka
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  #默认显示localhost,配置显示出ip
  instance:
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
    #默认心跳时间
    lease-renewal-interval-in-seconds: 30
    #删除时间间隔
    lease-expiration-duration-in-seconds: 90

同上再创建一个client

3.添加服务调用

client1

A.java

@RestController
@RequestMapping("/A")
public class A {

    @GetMapping("info")
    public String A(){
        return "Hello A";
    }
}

client2 resttemplate调用

ApplicationConfig.java

@Configuration
public class ApplicationConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

B.java

@RestController
@RequestMapping("/B")
public class B {
    @Autowired
    private RestTemplate restTemplate;
    
    @GetMapping("/info")
    public String B() {
        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://client1/A/info", String.class);
        return forEntity.toString();
    }
}

踩坑:

1.服务名不能有下划线_

2.调用服务需要@LoadBalanced

补充

EnableDiscoveryClient注解在common包中,通过项目的classpath来决定使用哪种实现,而EnableEurekaClient注解在netflix包中,只会使用eureka这种实现方式;

所以,使用EnableDiscoverClient,对任何注册中心都适用。而EnableEurekaClient是为eureka服务的。

推荐使用@EnableDiscoverClient

参考:SpringCloud Eureka参数配置项详解