spring cloud

130 阅读1分钟

服务发现 (Eureka)

1.客户端 (Client)

@EnableEurekaClient
@SpringBootApplication
public class EurekaClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication.class, args);
    }
}

application.properties

server.port=8763
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
spring.application.name=server-ui

2.服务端 (Server)

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

	public static void main(String[] args) {
		SpringApplication.run(EurekaServerApplication.class, args);
	}
}
server.port=8761
eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

断路由(Hystrix)

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class ServiceRibbonApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceRibbonApplication.class, args);
    }


    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
@HystrixCommand(fallbackMethod = "error")
public String test(String name) {
    return restTemplate.getForObject("http://server-ui/hello?name=" + name, String.class);
}

public String error(String name) {
    return "404" + name;
}

智能路由 (zuul)

@SpringBootApplication
@EnableZuulProxy
public class ServerZuulApplication {

	public static void main(String[] args) {
		SpringApplication.run(ServerZuulApplication.class, args);
	}
}
server.port=8769
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

spring.application.name=server-zuul

zuul.routes.api-a.path=/api-a/**
zuul.routes.api-a.serviceId=server-ribbon
zuul.routes.api-b.path=/api-b/**
zuul.routes.api-b.serviceId=server-feign

客户端负载平衡 (Ribbon)

public String test(String name) {
    return restTemplate.getForObject("http://server-ui/hello?name=" + name, String.class);
}
server.port=8764
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
spring.application.name=server-ribbon