Feign是Webservice服务的客户端,创建接口+注解就可完成,实现简单

  1. 客户端通过@EnableFeignClients开启Feign的支持功能

    
    
    1. @SpringBootApplication
    2. @EnableEurekaClient
    3. @EnableFeignClients
    4. @RestController
    5. public class TestApplication {
    6. public static void main(String[] args) {
    7. SpringApplication.run(TestApplication.class, args);
    8. }
    9. }
    <p>&nbsp;</p>
    </li>
    <li>定义接口,通过@FeignClient("remote-service")&nbsp; 注解指定服务名来绑定服务,再使用SpringMVC的注解@RequestMapping来绑定具体该服务提供的REST接口&nbsp;&nbsp;<span style="color:#f33b45;"><strong>注</strong>:服务名不区分大小写</span>
    <pre class="has" name="code" onclick="hljs.signin(event)"><code class="language-java hljs"><ol class="hljs-ln"><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="1"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"><span class="hljs-meta">@FeignClient</span>(name = <span class="hljs-string">"user-service"</span>)</div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="2"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserService</span> </span>{</div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="3"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> </div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="4"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> <span class="hljs-meta">@RequestMapping</span>(value = <span class="hljs-string">"/service/getUserinfo"</span>)</div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="5"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> <span class="hljs-function"><span class="hljs-keyword">public</span> Map&lt;String, Object&gt; <span class="hljs-title">getUserinfo</span><span class="hljs-params">(@RequestParam(value = <span class="hljs-string">"userid"</span>)</span> String userid)</span>;</div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="6"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> </div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="7"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line">}</div></div></li></ol></code><div class="hljs-button signin" data-title="登录后复制"></div></pre>
    </li>
    <li>创建Controller,注入接口,即可使用</li>

补充说明

上面中FeignClient的映射路径就是调用服务提供者的访问路径,根据访问路径调用方法。

05-11 20:18