1. 程式人生 > >五、SpringCloud服務呼叫(Feign介面物件模式)

五、SpringCloud服務呼叫(Feign介面物件模式)

第一步、在當前專案pom.xml中新增spring-cloud-starter-feign的jar包

<dependencies>
    <!-- ribbon -->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka</artifactId>
      <version>1.3.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-ribbon</artifactId>
      <version>1.3.4.RELEASE</version>
    </dependency>

    <!-- feign呼叫 -->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-feign</artifactId>
      <version>1.3.4.RELEASE</version>
    </dependency>

</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-parent</artifactId>
          <version>Brixton.SR5</version>
          <type>pom</type>
        </dependency>
    </dependencies>

第二步:在application.properties中配置eureka引數

eureka.client.serviceUrl.defaultZone=http://localhost:7777/eureka

第三步:建立cn.xxx.xxx.remote包,在建立定義xxxRemote遠端Feign介面,追加@FeignClient標記

@FeignClient(name="SUBJECT-SERVICE")//指定註冊服務名
public interface SubjectRemote {

    //方法參考Controller定義編寫
    @RequestMapping(value="/subject",method=RequestMethod.GET)
    public ResponseResult loadSubjects();

}

第四步:直接在Controller中注入SubjectRemote (遠端Feign物件呼叫遠端服務)介面


@Controller
@RequestMapping("/exam")
public class ExamController {
	
	@Autowired
	private SubjectRemote subjectRemote;
	
	
	@RequestMapping("/home.html")
	public String home(String token,ModelMap model){


		//呼叫http://localhost:8885/subject請求獲取所有學科資訊
		//url規則: http://註冊服務名/請求名
		ResponseResult result = subjectRemote.loadSubjects();

		……

		//將資料存入Model
		model.put("result", result);
		return "home";//templates/home.html
	}
	
}

第五步、新增@EnableFeignClients@EnableDiscoveryClient標記到啟動類

@EnableFeignClients//啟用Feign介面模式呼叫服務
@EnableDiscoveryClient//啟用服務註冊和查詢
@SpringBootApplication
public class ExamWebBootApplication {

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

}

第六步、啟動各服務測試