微服務------Spring-Cloud-Feign調用服務實現負載均衡

項目名稱爲spring-cloud-feign
1、使用IDEA工具創建一個springboot項目,選擇如下依賴
 
2、項目搭建完成後,配置如下:
 
3、刪除application.properties文件,新建application.yml配置文件,配置如下:
spring:
    application:
        name: eureka-feign-client
server:
    port: 8764
eureka:
    client:
        defaultZone:
             http://localhost:8761/eureka/  #註冊中心的地址(默認是這個地址,換成自己的地址,會報錯,暫時不知道怎麼解決,所以先使用默認地址)

4、在啓動類上添加註解, 使得這個應用具有Feign的功能

package com.etc.springcloudfeign;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class SpringCloudFeignApplication {

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

5、新建一個接口,訪問Eureka的服務

package com.etc.springcloudfeign.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
* Feign需要新增一個接口HelloService
* 應用啓動時Feign就會使用動態代碼機制根據我們所定義的接口生成相應的類實例,並注入到Spring的應用上下文中。
* 在使用方式上,可以像使用普通Bean一樣使用該服務。
*/
//這裏需要注意,一定要對該接口添加@FeignClient註解,@FeignClient註解中的name屬性值設置爲微服務名稱:service-hello,這樣Feign就可以通過Eureka服務器獲取微服務實例,並進行調用
@FeignClient(value="service-hello")//指明調用 service-hello服務
public interface HelloService {

//注意請求的地址一定要與用戶微服務所提供的地址一致
@RequestMapping(value="/hello",method = RequestMethod.GET)
    public String hello(@RequestParam(value="name") String name);
}

6、新建一個Controller類,訪問Service的方法

package com.etc.springcloudfeign.controller;

import com.etc.springcloudfeign.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController //表示這是一個控制器
public class HelloController {
    @Autowired
    HelloService helloService;

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

7、啓動應用,再次訪問註冊中心,如下:

 
8、頁面調用Controller類,訪問如下:
 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章