0
点赞
收藏
分享

微信扫一扫

(二)注册中心Eureka

whiteMu 2022-01-06 阅读 102

本节内容

加入Eureka注册中心

eurekaServer模块

pom

<dependencies>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
	</dependency>
</dependencies>

配置文件

server:
  port: ${port:9001 }
eureka:
  server:
    enable-self-preservation: false # 关闭自我保护
    eviction-interval-timer-in-ms: 10000 # 剔除服务间隔
  instance:
    hostname: localhost # 实例名
  client:
    register-with-eureka: false # 不注册
    fetch-registry: false # 不拉取
    service-url: # 地址
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

启动类

@SpringBootApplication
@EnableEurekaServer
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class);
	}
}

配置,运行,打开URL:http://localhost:9001/
在这里插入图片描述
成功!

改造生产者

pom添加

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

配置文件

server:
  port: ${port:9101}
spring:
  application:
    name: producer
eureka:
  client:
    register-with-eureka: true # 注册
    fetch-registry: false # 不拉取
    service-url: # 地址
      defaultZone: http://localhost:9001/eureka/

启动类

@SpringBootApplication
@EnableEurekaClient
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class);
	}
}

运行结果:
在这里插入图片描述
在这里插入图片描述

改造消费者

pom添加

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

配置文件

server:
  port: ${port:9201}
spring:
  application:
    name: consumer
eureka:
  client:
    register-with-eureka: true # 注册
    fetch-registry: true # 拉取
    service-url: # 地址
      defaultZone: http://localhost:9001/eureka/

启动类

@SpringBootApplication
@EnableEurekaClient
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class);
	}

	@Bean
	@LoadBalanced
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}
}

控制器

@RestController
public class ConsumerController {

	@Autowired
	RestTemplate restTemplate;

	private static final String url = "http://producer";

	@RequestMapping("/query")
	public Student fun1() {
		return restTemplate.getForObject(url + "/student", Student.class);
	}
}

运行结果:
在这里插入图片描述
在这里插入图片描述
成功!

举报

相关推荐

0 条评论