• 学习spring cloud记录3服务远程调用


    前言

    记录一个非常简单的远程调用方式,在spring cloud微服务中,服务之间时如何进行调用的?在学习通过服务名调用方式之前,先学一种非常简单的调用方式,那就是通过url进行调用,此url为ip+端口号+地址的方式

    使用

    spring提供了工具RestTemplate,在每次进行调用时需要new一个RestTemplate对象,然后进行调用接口,在spring cloud中,可以在启动类中注册RestTemplate对象,在后面的代码中直接注入即可,无需new对象。

    在启动类中添加代码:

     1 package priv.sinoam.demoorder;
     2 
     3 import org.springframework.boot.SpringApplication;
     4 import org.springframework.boot.autoconfigure.SpringBootApplication;
     5 import org.springframework.context.annotation.Bean;
     6 import org.springframework.web.client.RestTemplate;
     7 
     8 /**
     9  * @author 龙谷情
    10  */
    11 @SpringBootApplication
    12 public class DemoOrderApplication {
    13 
    14     public static void main(String[] args) {
    15         SpringApplication.run(DemoOrderApplication.class, args);
    16     }
    17 
    18     /**
    19      * 创建RestTemplate并注入Spring容器
    20      * @return
    21      */
    22     @Bean
    23     public RestTemplate restTemplate(){
    24         return new RestTemplate();
    25     }
    26 
    27 }

    调用时如此调用即可:

     1     @Autowired
     2     private RestTemplate restTemplate;
     3     public Map<String, Object> test1() {
     4         DemoOrderInfo demoOrderInfo = demoOrderInfoDao.selectById(1);
     5         Map<String, Object> map = new HashMap<>(16);
     6         map.put("order", demoOrderInfo);
     7         //调用demo-user里面的请求
     8         String url = "http://localhost:9001/demouser/user/test";
     9         Map<String, Object> map2 = restTemplate.getForObject(url, Map.class);
    10         map.put("user", map2);
    11         return map;
    12     }

    本次实验在order服务中调用user接口。第9行可根据需要的类型进行修改,本次使用Map类型。

    结束

    一次非常简单的记录,时间少,就少记录一点。下面学习记录Eureka服务

  • 相关阅读:
    表达式目录树(Expression)
    六大设计原则【单一职责】【里氏替换】【 迪米特法则】【依赖倒置原则】【接口隔离原则】【开闭原则】
    lambda,linq
    c#中的特性Attribute
    CentOS7部署Nginx
    NetCore项目的部署
    ABP+NetCore+Vue.js实现增删改查
    Abp数据库迁移注意事项
    MVC分页
    AspNet5 Changes to [Activate] in beta-5
  • 原文地址:https://www.cnblogs.com/lgqrlchinese/p/16109785.html
Copyright © 2020-2023  润新知