Spring Cloud -- 使用Feign声明式服务调用

上一篇博客我们讲了如何去创建注册中心并注册服务,那注册中心的服务我们要如何去调用呢?这里我们先使用Feign声明式服务调用,这里以UserController去调用DictionaryController里的服务

1.引入依赖:

		<!-- Feign声明式服务调用依赖 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</artifactId>
			<version>1.4.0.RELEASE</version>
		</dependency>

2.开启Feign,主方法必须要配置两个注解:

@EnableDiscoveryClient
@EnableFeignClients

3.创建一个服务调用接口:

package com.id0304.user.feign;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

@Service	//注入spring容器
@FeignClient("dictionary")	//这里写服务名称,即spring-application-name配置的属性名称
public interface FeignService {
    @GetMapping("/hello")	//这里写对应服务的url
    public String hello();
}

4.在UserController调用DictionaryController的hello方法

UserController:

package com.id0304.user.controller;

import com.id0304.user.feign.FeignService;
import com.id0304.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    FeignService feignService;	//注入该对象,即可调用

    @GetMapping("/test")
    public @ResponseBody String test(){
        return feignService.hello();	//调用hello方法,实际上就是远程调用了DictionaryService里的hello方法
    }
}

DictionaryController:

package com.id0304.dictionary.controller;

import com.id0304.common.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DictionaryController {
    @GetMapping("/hello")	//这里的url要跟上面Feign接口调用的url一致
    public @ResponseBody String hello() {	//可以给UserController调用
        return "hello!";
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值