springcloud 第三步 微服务间的调用例子(这里使用Feign)

Feign默认集成了Ribbon,采用基于接口的注解,并和Eureka结合,默认实现了负载均衡的效果,这里选择它,因为我觉得它更好用,废话不多说,开始实验:
1.新建一个spring-boot工程,取名feign_test
2.pom.xml中添加eureka、fein、web的起步依赖(只列出关键配置)
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Camden.SR5</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>




3.在application.yml文件中配置如下:
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8765
spring:
  application:
    name: feign_test


4.main函数添加注解:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignTestApplication {


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


5.在服务提供者service-hi(即我的博客springcloud第二步中新建的eureka客户端)中添加接口方法如下:
@RestController
public class ServiceHiApplication {
    @Value("${server.port}")
    String port;
    @RequestMapping("/hi")
    public String home(@RequestParam String name) {
        return "hi "+name+"(from port:" +port+")";
    }
}




6.定义一个feign接口,通过@ FeignClient(“服务名”),来指定调用哪个服务。比如在代码中调用了service-hi服务的“/hi”接口,代码如下:


@FeignClient(value = "service-hi")
public interface IHiService {
    @RequestMapping(value = "/hi",method = RequestMethod.POST)
    String sayHi(@RequestParam(value = "name") String name);
}


7.在Web层的controller层,对外暴露一个”/hello”的API接口,通过上面定义的Feign客户端IHiService 来消费服务。代码如下:
@RestController
public class HiController {


    @Autowired
    IHiService hiService 
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String sayHi(@RequestParam String name){
        return hiService.sayHi(name);
    }
}


8.启动程序,发现Eureka服务中多了一条注册信息:






9.多次访问http://localhost:8765/hi?name=czy,浏览器交替显示:


    hi czy(from port:7071)


    hi czy(from port:7072)

猜你喜欢

转载自blog.csdn.net/c77061900/article/details/80067781
今日推荐