搭建nacos注册中心
1、下载启动nacos
2、在父pom添加依赖管理
-
<properties> <cloud-alibaba.version>0.2.2.RELEASE</cloud-alibaba.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>${cloud-alibaba.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
3、配置Nacos客户端的pom依赖
-
<!--服务注册--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>
3、添加服务配置文件
-
#微服务名称 spring.application.name=demo # nacos服务地址 spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
4、在微服务启动类添加注解
-
@EnableDiscoveryClient
Feign服务调用
1、配置微服务的pom依赖
-
<!--服务调用--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
2、在微服务启动类上添加注解
-
@EnableFeignClients
3、Feign调用实例
-
使用到的注解
- @FeignClient注解用于指定从哪个服务(nacos注册中心的服务名)中调用功能 ,名称与被调用的服务名保持一致。位于类上
- @GetMapping注解用于对被调用的微服务进行地址映射。
- @PathVariable注解一定要指定参数名称,否则出错
- @Component注解防止,在其他位置注入CodClient时idea报错
-
代码样例
-
//demo1微服务client包下TestClient @FeignClient("demo2") @Component public interface TestClient { @GetMapping("/demo2/test") public String test(); }
-
//demo1微服务controller包下 @Controller @RequestMapping("/demo1") public class HomeController { @Autowired public TestClient testClient; @ResponseBody @GetMapping("feignTest") public String test() { String test = testClient.test(); return test; } }
-
//demo2微服务controller包下 @Controller @RequestMapping("/demo2") public class HomeController { @ResponseBody @GetMapping("test") public String test() { return "demo2: test"; } }
-
Hystrix熔断器
1、配置微服务pom依赖
-
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> <!--hystrix依赖,主要是用 @HystrixCommand --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
2、添加服务配置文件
-
#开启熔断机制 feign.hystrix.enabled=true # 设置hystrix超时时间,默认1000ms hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=6000
3、在client包里面创建熔断器实现类
-
@Component public class HystrixTest implements TestClient{ @Override public String test() { return "demo1: feign time out"; } }
4、修改client接口的注解
-
@FeignClient(name = "demo2", fallback = HystrixTest.class) @Component public interface TestClient { @GetMapping("/demo2/test") public String test(); }