springCloud(二)feign

24 阅读1分钟

要求

通过feign,实现member模块调用business模块的方法

business

配置增加模块应用名字

application.properties

spring.application.name=business

增加测试用的方法 controller/HomeController

@RestController
public class HomeController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello World! Business!";
    }
}

member模块

增加依赖

pom.xml

        <!--远程调用openfeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--openfeign默认使用的是loadBalance的负载均衡器  -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-loadbalancer</artifactId>
        </dependency>

配置增加模块应用名字

application.properties

spring.application.name=member

增加feign调用 feign/BusinessFeign

@FeignClient(name = "business", url = "http://127.0.0.1:8003/business")
public interface BusinessFeign {
    @GetMapping("/hello")
    String hello();
}

主入口增加feign注解

MemberApplication

@EnableFeignClients

@SpringBootApplication
@EnableFeignClients("com.example.springCloud3.member.feign")
public class MemberApplication {
    private static final Logger LOG = LoggerFactory.getLogger(MemberApplication.class);
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MemberApplication.class);
        Environment env = app.run(args).getEnvironment();
        LOG.info("启动成功!!");
        LOG.info("测试地址: \thttp://127.0.0.1:{}/hello", env.getProperty("server.port"));
    }
}

测试调用

@RestController
public class TestController {
    private static final Logger LOG = LoggerFactory.getLogger(TestController.class);

    @Resource
    BusinessFeign businessFeign;
    @GetMapping("/hello")
    public String hello() {
        String businessHello = businessFeign.hello();
        LOG.info("feign调用business方法:------"+businessHello);
        return "Hello World!";
    }
}

image.png