Spring Cloud Alibaba学习03OpenFeign基本使用

OpenFeight是由Spring Cloud官方开发的组件,它是一种声明式,模板化的HTTP客户端。

在Spring Cloud中使用OpenFeign,可以做到使用HTTP请求远程服务时与调用本地方法一样的编程体验,开发者完全感知不到是在调用远程方法,更感知不到这是HTTP请求。同时OpenFeign通过集成Ribbon实现客户端的负载均衡。使用OpenFeign可以代替RestTemplate。

1、添加新模块,作为服务提供者,cloud-jifen

使用IDEA创建新模块,在pom文件中引用:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud-demo01</artifactId>
        <groupId>org.yas</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>cloud-jifen</artifactId>
    <dependencies>
        <!-- web场景依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 端点监控场景依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- nacos场景依赖 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.yas</groupId>
            <artifactId>cloud-entity</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
</project>

添加配置文件,application.yml:

spring:
  application:
    name: cloud-jifen #服务名称,必须唯一
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #指定nacos服务地址
        username: nacos
        password: nacos
        # namespace: public
        # group: DEFAULT_GROUP
server:
  port: 9904

添加启动类:

 1 package com.yas;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
 6 
 7 @SpringBootApplication
 8 @EnableDiscoveryClient//开启服务注册与发现功能
 9 public class JifenApp {
10     public static void main(String[] args) {
11         SpringApplication.run(JifenApp.class);
12     }
13 }

编写服务提供者controller:

 1 package com.yas.controller;
 2 
 3 import com.yas.Customer;
 4 import com.yas.Jifen;
 5 import org.springframework.beans.factory.annotation.Value;
 6 import org.springframework.web.bind.annotation.*;
 7 
 8 import java.util.ArrayList;
 9 import java.util.HashMap;
10 import java.util.List;
11 import java.util.Map;
12 
13 @RestController
14 @RequestMapping("/jifen")
15 public class JifenController {
16 
17     @RequestMapping("/save")
18     public Map save(@RequestBody Jifen jifen){
19         System.out.println("调用了积分保存接口");
20         System.out.println(jifen);
21         Map map = new HashMap();
22         map.put("isSuccess",true);
23         map.put("msg","save success");
24         return map;
25     }
26 
27     @RequestMapping("/update")
28     public Map update(@RequestBody Jifen jifen){
29         System.out.println(jifen);
30         Map map = new HashMap();
31         map.put("isSuccess",true);
32         map.put("msg","update success");
33         return map;
34     }
35 
36     @RequestMapping("/delete")
37     public Map deleById(Integer jifenId){
38         System.out.println("删除id为"+jifenId+"的积分信息");
39         Map map = new HashMap();
40         map.put("isSuccess",true);
41         map.put("msg","delete success");
42         return map;
43     }
44 
45     @RequestMapping("/find/{jifenId}")
46     public Jifen findJifenById(@PathVariable Integer jifenId){
47         System.out.println("一查询到"+jifenId+"积分数据");
48         return new Jifen(jifenId,12,jifenId+"号积分");
49     }
50 
51     @RequestMapping("/search")
52     public Jifen search(@RequestParam Integer uid,@RequestParam String type){
53         System.out.println("uid:"+uid+",type:"+type);
54         return new Jifen(uid,12,type);
55     }
56 
57     @RequestMapping("/searchByEntity")
58     public List<Jifen> searchMap(@RequestBody Jifen jifen){
59         System.out.println(jifen);
60         List<Jifen> jifens = new ArrayList<>();
61         jifens.add(new Jifen(110,12,"下单积分"));
62         jifens.add(new Jifen(111,10,"支付积分"));
63         return jifens;
64     }
65 }

2、接口模块,cloud-api:

使用IDEA建立新模块,pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud-demo01</artifactId>
        <groupId>org.yas</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>cloud-api</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.yas</groupId>
            <artifactId>cloud-entity</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
</project>

添加OpenFeign接口:

 1 package com.api;
 2 
 3 import com.yas.Jifen;
 4 import org.springframework.cloud.openfeign.FeignClient;
 5 import org.springframework.web.bind.annotation.PathVariable;
 6 import org.springframework.web.bind.annotation.RequestBody;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestParam;
 9 
10 import java.util.List;
11 import java.util.Map;
12 
13 @FeignClient("cloud-jifen")
14 @RequestMapping("/jifen")
15 public interface JifenApi {
16     @RequestMapping("/save")
17     Map save(@RequestBody Jifen jifen);
18 
19     @RequestMapping("/update")
20     Map update(@RequestBody Jifen jifen);
21 
22     @RequestMapping("/delete")
23     Map deleById(@RequestParam Integer jifenId);
24 
25     @RequestMapping("/find/{jifenId}")
26     Jifen findJifenById(@PathVariable Integer jifenId);
27 
28     @RequestMapping("/search")
29     Jifen search(@RequestParam Integer uid,@RequestParam String type);
30 
31     @RequestMapping("/searchByEntity")
32     List<Jifen> searchMap(@RequestBody Jifen jifen);
33 }

3、修改cloud-order模块:

pom文件增加新引用:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud-demo01</artifactId>
        <groupId>org.yas</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>cloud-order</artifactId>
    <dependencies>
        <!-- web场景依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 端点监控场景依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- nacos场景依赖 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.yas</groupId>
            <artifactId>cloud-entity</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.yas</groupId>
            <artifactId>cloud-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
</project>

启动类修改如下:

 1 package com.yas;
 2 
 3 import com.rule.MyRule;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
 7 import org.springframework.cloud.client.loadbalancer.LoadBalanced;
 8 import org.springframework.cloud.netflix.ribbon.RibbonClient;
 9 import org.springframework.cloud.openfeign.EnableFeignClients;
10 import org.springframework.context.annotation.Bean;
11 import org.springframework.web.client.RestTemplate;
12 
13 @SpringBootApplication
14 @EnableDiscoveryClient
15 @RibbonClient(name = "cloud-goods",configuration = {MyRule.class})
16 @EnableFeignClients(basePackages = {"com.api"})//开启OpenFeign
17 public class OrderApp {
18     public static void main(String[] args) {
19         SpringApplication.run(OrderApp.class);
20     }
21 
22 //    @Bean
23 //    @LoadBalanced//使用Ribon调用服务,将域名请求变为服务地址请求
24 //    public RestTemplate initRestTemplate() {
25 //        return new RestTemplate();
26 //    }
27 }

编写测试controller:

 1 package com.yas.controller;
 2 
 3 import com.api.JifenApi;
 4 import com.yas.Jifen;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.RestController;
 8 
 9 import java.util.Map;
10 
11 @RestController
12 @RequestMapping("/feign")
13 public class FeignController {
14 
15     @Autowired
16     JifenApi jifenApi;
17 
18     @RequestMapping("/save")
19     public Map save(){
20         Jifen jifen = new Jifen(1,10,"注册积分");
21         return jifenApi.save(jifen);
22     }
23 
24     @RequestMapping("/update")
25     public Map update(){
26         Jifen jifen = new Jifen(1,10,"注册积分");
27         return jifenApi.update(jifen);
28     }
29 
30     @RequestMapping("/delete")
31     public Map delete(){
32         return jifenApi.deleById(1);
33     }
34 
35     @RequestMapping("/find")
36     public Jifen find(){
37         return jifenApi.findJifenById(1);
38     }
39 }

4、测试:

使用postman请求:localhost:9900/feign/save

总结:使用OpenFeign后,可以不再显示的调用RestTemplate的API了,而是像调用本地资源一样的方式调用远程服务。

原文地址:https://www.cnblogs.com/asenyang/p/15540433.html