微服务------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类,访问如下:
 
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值