SpringCloud 三种服务调用方式,你学会了吗?

点击上方“芋道源码”,选择“设为星标

管她前浪,还是后浪?

能浪的浪,才是好浪!

每天 10:33 更新文章,每天掉亿点点头发...

源码精品专栏

 

来源:blog.csdn.net/qq_21790633/

article/details/105182750

4dda25b5756df815428ef677c2c71684.jpeg


本文主要介绍SpringCloud中调用服务的方式:

  • Spring DiscoveryClient

  • 支持 Ribbon 的 RestTemplate

  • Feign客户端

服务测试环境

测试中,发现Netflix的Eureka服务层采用。

主要步骤如下:

1.引入Eureka所需的依赖

<!--eureka服务端-->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka-server</artifactId>
  </dependency>
<!--客户端-->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

2.修改配置文件

服务端:

eureka:
 instance:
  hostname: eureka9001.com #eureka服务端的实例名称
  instance-id: eureka9001
client:
  register-with-eureka: false #false表示不向注册中心注册自己
  fetch-registry: false # #false 表示自己就是注册中心,职责就是维护服务实例,并不需要去检索服务
  service-url:
  defaulteZone: http://127.0.0.1:9001

客户端1:

server:
  port: 8002
spring:
  application:
    name: licensingservice
eureka:
  instance:
    instance-id: licensing-service-8002
    prefer-ip-address: true
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://127.0.0.1:9001/eureka/,

客户端2:

server:
 port: 8002
spring:
 application:
   name: licensingservice
eureka:
 instance:
   instance-id: licensing-service-8002
   prefer-ip-address: true
 client:
   register-with-eureka: true
   fetch-registry: true
   service-url:
     defaultZone: http://127.0.0.1:9001/eureka/,

一组微服务的不同实例采办服务名称不同,不同的实例ID不同,不同,spring.application.nameeureka.instance.instance-id

3.启动服务

服务端:

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerPort9001_App {
  public static void main(String[] args) {
    SpringApplication.run(EurekaServerPort9001_App.class,args);
  }
}

客户端:

@SpringBootApplication
@RefreshScope
@EnableEurekaClient
public class LicenseApplication_8002 {
    public static void main(String[] args) {
        SpringApplication.run(LicenseApplication_8002.class, args);
    }
}

4.测试

进入到Eureka服务端地址,我这是127.0.0.1:9001,可以查看注册到注册中心的服务。

标签:

c313dcc59765b7b6a146473a769e0d77.png

注意:Eureka通过两次服务检测均到通过,服务将在间隔10秒内成功启动服务注册等待30秒。

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://gitee.com/zhijiantianya/ruoyi-vue-pro

  • 视频教程:https://doc.iocoder.cn/video/

消费者

1.发现客户端方式

服务中既是服务是微信也可以是调用者,消费者配置和上面配置的大体参考一致,依赖及配置服务端启动方式EnableEurekaClient:监听启动。

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class ConsumerApplication_7002 {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication_7002.class, args);
    }
}

核心配置类:

@Component
public class ConsumerDiscoveryClient {

  @Autowired
  private DiscoveryClient discoveryClient;

  public ServiceInstance getServiceInstance() {
    List<ServiceInstance> serviceInstances = discoveryClient.getInstances("licensingservice");
    if (serviceInstances.size() == 0) {
      return null;
    }
    return serviceInstances.get(0);
  }

  public String getUrl(String url) {
    ServiceInstance serviceInstance=this.getServiceInstance();
    if (serviceInstance==null)
      throw new RuntimeException("404 ,NOT FOUND");
    String urlR=String.format(url,serviceInstance.getUri().toString());
    return urlR;
  }
}

通过DiscoveryClient从尤里卡中获取licensingservice服务的实例,并返回第一个实例。

测试控制器

@RestController
@RequestMapping("test")
public class TestController {
  //注意必须new,否则会被ribbon拦截器拦截,改变URL行为
  private RestTemplate restTemplate=new RestTemplate();
  @Autowired
  private ConsumerDiscoveryClient consumerDiscoveryClient;
  @RequestMapping("/getAllEmp")
  public List<Emp> getAllLicense(){
    String url=consumerDiscoveryClient.getUrl("%s/test/getAllEmp");
    return restTemplate.getForObject(url,List.class);
  }
}

测试:

  1. 调试信息

3d4649553fb0f60d3cf1dc7b622f6603.png从该图可以看到licensingservice,拥有两个服务实例,并可以查看实例信息。

  1. 页面返回信息

b21d49ac28cdb4015090e3842f02753d.png

成功查询到数据库存储信息。

2.Ribbon方式功能的Spring RestTemplate

同上。

核心配置类:

//指明负载均衡算法
@Bean
public IRule iRule() {
  return new RoundRobinRule();
}

@Bean
@LoadBalanced //告诉Spring创建一个支持Ribbon负载均衡的RestTemplate
public RestTemplate restTemplate() {
  return new RestTemplate();
}

设置均衡方式为轮询方式。

测试类:

@RestController
@RequestMapping("rest")
public class ConsumerRestController {

    @Autowired
    private RestTemplate restTemplate;
    private final static String SERVICE_URL_PREFIX = "http://LICENSINGSERVICE";

    @RequestMapping("/getById")
    public Emp getById(Long id) {
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        paramMap.add("id", id);
        return restTemplate.postForObject(SERVICE_URL_PREFIX + "/test/getById", paramMap, Emp.class);
    }
}

测试结果:

  • 第一次:

eed45a7688be20cc016f2f994e5e22f3.png
  • 第二次:

e4f76ea75c1b9a6bca640b3665bfb24c.png
  • 第三次:

dffbca95505c9fbf5c412b6923ff4fc0.png

因为采用轮询平均方式分别使用不同的服务实例,未区别,将名称确定了一定的。

这上面,Ribbon 是对第一种方式的封装方式和不同的负载率。 Feign的方式则大大降低了开发客户端和提升速度。

3.feign客户端方式

引入依赖:

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

主要代码:

@FeignClient(value = "LICENSINGSERVICE",fallbackFactory = ServiceImp.class)
public interface ServiceInterface {

  @RequestMapping("/test/getById")
  Emp getById(@RequestParam("id") Long id);

  @RequestMapping("/test/getLicenseById")
  License getLicenseById(@RequestParam("id") Long id);

  @RequestMapping("/test/getAllEmp")
  List<Emp> getAllLicense();
}
@Component
public class ServiceImp implements FallbackFactory<ServiceInterface> {

    @Override
    public ServiceInterface create(Throwable throwable) {
        return new ServiceInterface() {
            @Override
            public Emp getById(Long id) {
                Emp emp = new Emp();
                emp.setName("i am feign fallback create");
                return emp;
            }

            @Override
            public License getLicenseById(Long id) {
                return null;
            }

            @Override
            public List<Emp> getAllLicense() {
                return null;
            }
        };
    }
}

注采用接口模式,通过指定服务名以及方法,在服务开发结果不佳时,方便返回默认的,而不是一个不友好的错误。

主启动类:

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class Consumer_feign_Application_7004 {
    public static void main(String[] args) {
        SpringApplication.run(Consumer_feign_Application_7004.class, args);
    }
}

测试类:

@RestController
@RequestMapping("rest")
public class ConsumerRestController {
  @Autowired
  private ServiceInterface serviceInterface;

  @Autowired
  private RestTemplate restTemplate;
  @RequestMapping("/getById")
  public Emp getById(Long id) {
    return serviceInterface.getById(id);
  }
}

测试结果:

  • 正常测试:

87b04f9efcb332c14a751d5295cd13b2.png
  • 关闭两个实例,模拟服务实例死亡:

f2690c42e6c0ae943fd43fdebae26ae8.png

假装能够故障服务调用,也可以实现调用的服务时,友好的信息。

以此方式,由低上,从不同层次实现了SpringCloud中的微服务相互引用。



欢迎加入我的知识星球,一起探讨架构,交流源码。加入方式,长按下方二维码噢

e78cb7ed753322a752652fd396baafca.png

已在知识星球更新源码解析如下:

5695386b8d3752657b48b257e53f5b36.jpeg

21d8e158327541cc43895de63bf4c108.jpeg

a1037662290e5b9e7934814fd93a60a5.jpeg

eb3b48855a8be4ef26eb1132ebe482c9.jpeg

最近更新《芋道 SpringBoot 2.X 入门》系列,已经 101 余篇,覆盖了 MyBatis、Redis、MongoDB、ES、分库分表、读写分离、SpringMVC、Webflux、权限、WebSocket、Dubbo、RabbitMQ、RocketMQ、Kafka、性能测试等等内容。

提供近 3W 行代码的 SpringBoot 示例,以及超 4W 行代码的电商微服务项目。

获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。

文章有帮助的话,在看,转发吧。
谢谢支持哟 (*^__^*)
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值