Spring Cloud feign 服务消费者

1.继承自https://www.cnblogs.com/BennyTitan/p/9178324.html 注册服务的过程

2.新建负载均衡Feign-Service客户端

新建maven项目,配置增加如下依赖:

pom.xml:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

application.yml:

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  instance:
   leaseRenewalIntervalInSeconds: 1
   leaseExpirationDurationInSeconds: 2
server:
  port: 8765
spring:
  application:
    name: service-feign
ServiceFeignApplication.java,
SchedualServiceHi.java
:
package com.bennytitan.servicefeign;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

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

    @Autowired
    SchedualServiceHi schedualServiceHi;
    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    public String sayHi(@RequestParam String name){
        return schedualServiceHi.sayHiFromClientOne(name);
    }

}
package com.bennytitan.servicefeign;

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

@FeignClient(value = "eurekaclient")
@Service
public interface SchedualServiceHi {
    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    String sayHiFromClientOne(@RequestParam(value = "name") String name);
}

启动服务,可以在http://localhost:8761 看到服务注册进来了:

然后多次访问http://localhost:8765/hi?name=forezp,可以看到返回的结果是对EUREKACLIENT 的交替访问:

 

posted @ 2018-06-19 13:50  鸭脖子  阅读(120)  评论(0编辑  收藏  举报