版权声明:转载请注明出处,谢谢 https://blog.csdn.net/m0_37867405/article/details/80213928
1. eureka服务注册
1.1注册中心,服务端
引入jar
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
主类增加注解@EnableEurekaServer
@SpringBootApplication
@EnableEurekaServer
public class Eureka7000Application {
public static void main(String[] args) {
SpringApplication.run(Eureka7000Application.class, args);
}
}
文件配置:application.yml
s.hello.com
www.hello.com
分别是自己注解hosts文件中主机指向地址,当部署到不同的机器使用不同的ip即可
---
spring:
profiles: 7080
application:
name: eureka-7080
server:
port: 7080
eureka:
client:
fetch-registry: false # 不需要检索服务
register-with-eureka: false # 不向自己注册
serviceUrl:
defaultZone: http://www.hello.com:7081/eureka
instance:
hostname: s.hello.com
prefer-ip-address: true
---
spring:
profiles: 7081
application:
name: eureka-7081
server:
port: 7081
eureka:
client:
fetch-registry: false # 不需要检索服务
register-with-eureka: false # 不向自己注册
serviceUrl:
defaultZone: http://s.hello.com:7080/eureka
instance:
hostname: www.hello.com
prefer-ip-address: true # eureka ha机制需要加上这个
1.2 eureka客户端,向server注册服务
mic-eureka-6000微服务客户端
主类:
@SpringBootApplication
@EnableDiscoveryClient
public class Eureka6000Application {
public static void main(String[] args) {
SpringApplication.run(Eureka6000Application.class, args);
}
}
配置文件
spring:
application:
name: eureka-6000 # 负载均衡的时候必须保持一致,注册到服务端的名称
eureka:
instance:
hostname: eureka01.com
prefer-ip-address: true
instance-id: eureka01.com # 负载均衡的时候此处不能一致,或者可以不写
client:
serviceUrl:
defaultZone: http://s.hello.com:7080/eureka,http://www.hello.com:7081/eureka
定义接口
@RestController
public class TestController {
@RequestMapping("/sayhello")
public String hello(){
return "hello-6001";
}
}
1.3 Ribbon使用eureka-6000
mic-ribbon-8000
@SpringBootApplication
@EnableEurekaClient
public class MicRibbon8000Application {
public static void main(String[] args) {
SpringApplication.run(MicRibbon8000Application.class, args);
}
}
配置文件
server:
port: 8000
eureka:
client:
service-url:
defaultZone: http://s.hello.com:7080/eureka, http://www.hello.com:7080/eureka
spring:
application:
name: ribbon-8000
配置负载均衡
@Configuration
public class ApplicationContext {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
使用eureka-6000中的接口
http://EUREKA-6000/sayhello
必须为mic-eureka-6000微服务中spring.application.name
的value
扫描二维码关注公众号,回复:
3252955 查看本文章
@RestController
public class ConsumerController {
private static final String COMMON_PATH = "http://EUREKA-6000/sayhello";
@Autowired
private RestTemplate restTemplate;
@GetMapping("/hello")
public String sayHello() {
return restTemplate.getForEntity(COMMON_PATH, String.class).getBody();
}
}