搭建eureka注册中心
eureka服务配置文件
server:
port: 10086 #服务端口
spring:
application:
name: register-eureka #服务名
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka/ #注册中心地址
eureka启动类配置
@SpringBootApplication
@EnableEurekaServer //标记eureka注册中心
public class RegisterEurekaApplication {
public static void main(String[] args) {
SpringApplication.run(RegisterEurekaApplication.class, args);
}
}
服务提供者 serve-eureka
serve-eureka配置
server.port=8080
spring.application.name=serve-eureka
eureka.client.service-url.defaultZone= http://localhost:10086/eureka/ ##连接注册中心
serve-eureka启动类
@SpringBootApplication
@EnableDiscoveryClient //标记时eureka服务
public class ServeEurekaApplication {
public static void main(String[] args) {
SpringApplication.run(ServeEurekaApplication.class, args);
}
}
服务消费者consume-eureka
consume-eureka配置
server.port=80
spring.application.name=consume-eureka
eureka.client.service-url.defaultZone= http://localhost:10086/eureka/
consume-eureka启动类
@SpringBootApplication
@EnableCircuitBreaker//开启Hystyix熔断
public class ConsumeEurekaApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumeEurekaApplication.class, args);
}
@Bean
@LoadBalanced //开启ribbon负载均衡
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
consume-eureka 服务入口
@RestController
@DefaultProperties(defaultFallback = "fallback") //全局熔断
public class LoginController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("login")
@HystrixCommand
public String login(@RequestParam String message){
System.out.println("restTemplate请求服务时直接使用服务名进行请求 可以实现负载均衡");
return restTemplate.getForObject("http://serve-eureka/index/"+message,String.class);
}
//全局熔断方法
public String fallback(){
return "请求超时";
}
}