springCloud:微服务的实现方式。
组件:
Eureka:注册中心
Zuul:服务网关
Ribbon:负载均衡
Feign:服务调用
Hystrix:熔断器
入门代码
前提:父工程为springboot,并且进行了jar包的版本管理
Eureka:注册中心,实现服务的注册和发现功能
1、导入坐标
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.2</version> </dependency> </dependencies>
2、创建启动类
@SpringBootApplication @EnableEurekaServer public class EurekaServer { public static void main(String[] args) { SpringApplication.run(EurekaServer.class); } }
3、添加配置文件
server: port: 8084 spring: application: name: eureka-server eureka: client: service-url: defaultZone: http://127.0.0.1:8084/eureka
Ribbon:负载均衡
Hystrix:熔断器
Feign:服务调用
Zuul:服务网关
示例代码:
1、导入坐标
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> </dependencies>
2、编写启动类
@EnableCircuitBreaker @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients /* @SpringCloudApplication */ public class ConsumerApplication { @Bean @LoadBalanced public RestTemplate restTemplate (){ return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class); } }
3、实现代码
@RestController @RequestMapping("consumer") public class ConsumerController { @Autowired private RestTemplate restTemplate; @Autowired private LoadBalancerClient client; @GetMapping("{id}") @HystrixCommand(fallbackMethod = "queryByIdFallback") public Account queryById(@PathVariable ("id") Integer id){ //List<ServiceInstance> instances = discoveryClient.getInstances("user_service"); //ServiceInstance instanceInfo = instances.get(0); ServiceInstance instance = client.choose("user_service"); String url = "http://"+instance.getHost()+":"+instance.getPort()+"/account/"+id; System.out.println(url); Account account = restTemplate.getForObject(url,Account.class); return account; } public Account queryByIdFallback(Integer id ){ return null; } }