SpringCloud-基于feign实现服务调用

一、maven配置

 com.wk.sc
    springcloud-demo
    1.0-SNAPSHOT

    
        1.8
        Greenwich.SR1
    

    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.4.RELEASE
        
    

    
       
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
            org.springframework.cloud
            spring-cloud-starter-openfeign
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

二、application.yml配置

server:
  port: 7071

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: service-feign

三、启动类

@SpringBootApplication
@EnableDiscoveryClient
@EnableEurekaClient
@EnableFeignClients
public class ServiceFeignApplication {

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

}

四、服务调用

/**
 * feign服务调用示例
 *
 */
@FeignClient(value = "service-hi")
public interface IHelloService {
    /**
     * 调用服务
     *
     * @param name
     * @return
     */
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    String sayHi(@RequestParam("name") String name);
}

只需要提供接口并调用服务就可以了

五、控制器调用服务

/**
 * feign远程调用
 *
 */
@RestController
public class HiController {

    @Autowired
    private IHelloService helloService;  //忽略IDE spring注入错误,该服务是在运行时注入的,所以项目未启动spring是没办法感知的

    @GetMapping(value = "/hi")
    public String sayHi(@RequestParam String name) {
        return helloService.sayHi(name);
    }

}

你可能感兴趣的:(SpringCloud-基于feign实现服务调用)