spring cloud(四) feign

spring cloud 使用feign进行服务间调用

1. 新建boot工程 pom引入依赖

<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-openfeign</artifactId>
</dependency>
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.启动类添加注解@EnableEurekaClient  @EnableFeignClients

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class WebWapApplication {

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

}

3. application.properties添加配置

server.port=8080
spring.application.name=web-wap
spring.main.allow-bean-definition-overriding=true
#eureka
eureka.client.service-url.defaultZone=http://localhost:9001/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}

4. 编写调用程序

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserFeignCilent userFeignCilent;

    @GetMapping("/getUserInfoList")
    public GlobalResult<List<UserInfoRespVo>> getUserInfoList(){
        return   userFeignCilent.getUserInfoList();
    }


    @GetMapping("/getUserInfo")
    public GlobalResult<UserInfoRespVo> getUserInfo(Integer id){
        return   userFeignCilent.getUserInfo(id);
    }
}


/**
 * 调用网关服务
 */
@FeignClient(name = "zuul-server")
@RequestMapping("/userService")
public interface UserFeignCilent {

    @GetMapping("/getUserInfoList")
    GlobalResult<List<UserInfoRespVo>> getUserInfoList();

    @GetMapping("/getUserInfo")
    GlobalResult<UserInfoRespVo> getUserInfo(@RequestParam("id") Integer id);


}

服务提供者 user-service

@RestController
public class UserController {
    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/getUserInfoList")
    public GlobalResult<List<UserInfoRespVo>> getUserInfoList() {
        return userInfoService.getUserInfoList();
    }

    @GetMapping("/getUserInfo")
    public GlobalResult<UserInfoRespVo> getUserInfo(Integer id) {
        return userInfoService.getUserInfo(id);
    }
}

5.调用结果

 

项目github 地址  https://github.com/yongxiangliu123/SpringCloud

posted @ 2019-06-25 10:56  农夫与蛇丶  阅读(179)  评论(0)    收藏  举报