微服务------Spring-Cloud-Feign调用服务实现负载均衡

项目名称为spring-cloud-feign
1、使用IDEA工具创建一个springboot项目,选择如下依赖
微服务------Spring-Cloud-Feign调用服务实现负载均衡_第1张图片
 
2、项目搭建完成后,配置如下:
微服务------Spring-Cloud-Feign调用服务实现负载均衡_第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、启动应用,再次访问注册中心,如下:

微服务------Spring-Cloud-Feign调用服务实现负载均衡_第3张图片

微服务------Spring-Cloud-Feign调用服务实现负载均衡_第4张图片
 
8、页面调用Controller类,访问如下:
微服务------Spring-Cloud-Feign调用服务实现负载均衡_第5张图片
 
 
参考博客: https://blog.csdn.net/forezp/article/details/81040965

你可能感兴趣的:(微服务)