SpringCloud学习笔记(三)feign———服务消费者

上篇讲到了服务消费者ribbon ,这篇我记录另一种服务消费者feign

简而言之 feign采用的是基于接口的注解 使用很方便    并且整合了ribbon

继续用我们之前的工程,启动serv 并且启动两个客户端,详情请看上篇有详细记录如何启动一个serv (8761) 两个client(8762、8763)

首先创建feign的工程,还是一个全新的springboot工程,

需要依赖

web

eureka

feign

创建好之后 进行配置 向注册中心注册

这里要多加一个@EnableFeignClients注解 表明我们要是使用feign消费服务啦~

package com.chunying.feign;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class FeignApplication {

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

application.properties配置 和以前的相同 

server.port=8765

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

spring.application.name=service_feign

端口8765  服务名service_feign

接下来写测试类service,注意feign是基于接口的,所以要创建一个interface

注解@FeignClient(value="服务名") 表明要调用哪个服务

方法是调用服务中的具体哪个接口,包括参数等

package com.chunying.feign.service;

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

/**
 * @author chunying
 */
@FeignClient(value = "hello")
public interface HelloService {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String helloFromClient(@RequestParam(value="name") String name);

}


然后写一个controller 调用我们的service

package com.chunying.feign.Controller;

import com.chunying.feign.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * @author chunying
 */
@RestController
public class HelloController {

    @Autowired
    private HelloService helloService;

    @RequestMapping(value = "/hello" , method = RequestMethod.GET)
    public String hello(@RequestParam String name) {
        return helloService.helloFromClient(name);
    }

}
 
 

是不是很简单呢,启动工程

页面出现证明注册成功啦

访问http://localhost:8765/hello?name=ying 

交替出现结果

hello!8762,ying,come here

hello!8763,ying,come here


证明成功了,其实和ribbon是差不多的  只是实现方式是基于接口的了 ,写起来更方便了

两种服务消费者就记录完毕了~~欢迎讨论学习




猜你喜欢

转载自blog.csdn.net/java_ying/article/details/79868264
今日推荐