Spring Cloud—三、使用Spring Cloud实现微服务

业务:
1.商品微服务:通过商品id查询商品的服务。
2.订单微服务:创建订单时,通过调用商品的微服务进行查询商品数据。

业务.png

说明:
1.对于商品微服务而言,商品微服务是服务的提供者,订单微服务是服务的消费者。
2.对于订单微服务而言,订单微服务是服务的提供者,人是服务的消费者。

3.1、实现商品微服务

3.1.1、创建工程
创建工程.png
3.1.2、导入依赖
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
3.1.3、创建实体Item
package cn.zuoqy.springclouddemoitem.model;

/**
* Created by zuoqy on 14:05 2018/10/22.
*/
public class Item {

    private Long id;
    private String title;
    private String pic;
    private Long price;

    public Item(){};

    public Item(Long id, String title, String pic, Long price) {
        this.id = id;
        this.title = title;
        this.pic = pic;
        this.price = price;
    }
}
3.1.4、编写ItemService

编写itemService用于实现具体的商品查询逻辑,为了方便,我们并不真正的连接数据库,而是做模拟实现。

package cn.zuoqy.springclouddemoitem.service;

import cn.zuoqy.springclouddemoitem.model.Item;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
* Created by zuoqy on 14:10 2018/10/22.
*/
@Service
public class ItemService {

    public Item queryItemById(Long id) {
        return MAP.get(id);
    }

    private static final Map<Long, Item> MAP = new HashMap<>();

    static {
        MAP.put(1L,new Item(1L, "商品标题1", "http://图片1", 100L));
        MAP.put(2L,new Item(2L, "商品标题2", "http://图片2", 100L));
        MAP.put(3L,new Item(3L, "商品标题3", "http://图片3", 100L));
        MAP.put(4L,new Item(4L, "商品标题4", "http://图片4", 100L));
        MAP.put(5L,new Item(5L, "商品标题5", "http://图片5", 100L));
        MAP.put(6L,new Item(6L, "商品标题6", "http://图片6", 100L));
    }
}
3.1.5、编写ItemController
package cn.zuoqy.springclouddemoitem.controller;

import cn.zuoqy.springclouddemoitem.model.Item;
import cn.zuoqy.springclouddemoitem.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Created by zuoqy on 14:16 2018/10/22.
*/
@RestController
@RequestMapping(value = "item")
public class ItemController {

    @Autowired
    private ItemService itemService;

    /**
    * 对外提供接口服务,查询商品信息
    */
    @GetMapping(value = "query/{id}")
    public Item queryItemById(@PathVariable("id") Long id) {
        return itemService.queryItemById(id);
    }
}

@RestController注解说明:

RestController注解.png

从源码可以看出,这是一个组合注解,组合了@Controller和Response注解。相当于我们同时写了这2个注解。
@GetMapping注解说明:
GetMapping注解.png

@GetMapping注解是@RequestMapping(method=RequestMethod.GET)简写方式。其功能都是一样的。
同理还有其它注解:@DeleteMapping,@PostMapping,@PutMapping...

3.1.6、编写application.properties文件

spring Boot以及spring Cloud项目支持ymlproperties格式的配置文件。
yml格式是YAML(Yet Another Markup Language)编写的格式,YAML和properties格式的文件是相互转化的。如:

Server:
    prot:18100

等价于

server.port=18100

配置文件的示例:
application.properties.png
3.1.7、启动程序测试
测试结果.png

3.2、实现订单微服务

3.2.1、创建工程springcloud-demo-order (同3.1.1)
3.2.2、导入依赖 (同3.1.2)
3.2.3、创建Order实体
package cn.zuoqy.springclouddemoorder.model;

import java.util.Date;
import java.util.List;

/**
* Created by zuoqy on 14:29 2018/10/22.
*/
public class Order {

    private String orderId;
    private Long userId;
    private Date createDate;
    private Date updateDate;
    private List<OrderDetail> orderDetailList;

    public Order() {}

    public Order(String orderId, Long userId, Date createDate, Date updateDate, List<OrderDetail> orderDetailList) {
        this.orderId = orderId;
        this.userId = userId;
        this.createDate = createDate;
        this.updateDate = updateDate;
        this.orderDetailList = orderDetailList;
    }
}
3.2.4、创建订单详情OrderDetail实体
package cn.zuoqy.springclouddemoorder.model;

/**
* Created by zuoqy on 14:29 2018/10/22.
*/
public class OrderDetail {

    private String orderId;

    private Item item = new Item();

    private OrderDetail() {}

    public OrderDetail(String orderId, Item item) {
        this.orderId = orderId;
        this.item = item;
    }
}
3.2.5、将商品微服务中的Item类拷贝到当前工程
Item.png
3.2.6、编写ItemService
package cn.zuoqy.springclouddemoorder.service;

import cn.zuoqy.springclouddemoorder.model.Item;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
* Created by zuoqy on 14:43 2018/10/22.
*/
@Service
public class ItemService {

    @Autowired
    private RestTemplate restTemplate;

    public Item queryItemById(Long id) {
        return this.restTemplate.getForObject("http://127.0.0.1:8081/item/"+id,Item.class);
    }
}
3.2.7、编写OrderService

该Service实现的根据订单Id查询订单的服务,为了方便测试,我们将构造数据实现,不采用查询数据库的方式。

package cn.zuoqy.springclouddemoorder.service;

import cn.zuoqy.springclouddemoorder.model.Item;
import cn.zuoqy.springclouddemoorder.model.Order;
import cn.zuoqy.springclouddemoorder.model.OrderDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* Created by zuoqy on 14:34 2018/10/22.
*/
@Service
public class OrderService {

    @Autowired
    private ItemService itemService;

    /**
    * 根据订单id查询订单数据
    */
    public Order queryOrderById(String orderId) {
        Order order = MAP.get(orderId);
        if (null == order) {
            return null;
        }
        List<OrderDetail> orderDetails = order.getOrderDetailList();
        for (OrderDetail orderDetail: orderDetails) {
            Item item = this.itemService.queryItemById(orderDetail.getItem().getId());
            if (null == item) continue;
            orderDetail.setItem(item);
        }
        return order;
    }


    private static final Map<String, Order> MAP = new HashMap<>();

    static {
        Order order = new Order();
        order.setOrderId("9527order");
        order.setCreateDate(new Date());
        order.setUpdateDate(new Date());
        order.setUserId(9527L);
        List<OrderDetail> orderDetails = new ArrayList<>();
        Item item = new Item();
        item.setId(2L);
        orderDetails.add(new OrderDetail(order.getOrderId(),item));
        Item item2 = new Item();
        item2.setId(3L);
        orderDetails.add(new OrderDetail(order.getOrderId(),item2));
        order.setOrderDetailList(orderDetails);
        MAP.put(order.getOrderId(),order);
    }
}
3.2.8、编写OrderController
package cn.zuoqy.springclouddemoorder.controller;

import cn.zuoqy.springclouddemoorder.model.Order;
import cn.zuoqy.springclouddemoorder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Created by zuoqy on 14:56 2018/10/22.
*/
@RestController
@RequestMapping(value = "order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping(value = "/query/{orderId}")
    public Order queryOrderById(@PathVariable("orderId") String orderId) {
        return orderService.queryOrderById(orderId);
    }
}
3.2.9、向Spring容器中定义RestTemplate对象
package cn.zuoqy.springclouddemoorder;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class SpringcloudDemoOrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringcloudDemoOrderApplication.class, args);
    }

    @Bean //向Spring容器中定义RestTemplate对象
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
3.2.10、编写application.properties
application.properties.png
3.2.11、启动测试
测试结果.png

3.3、添加okHttp的支持

okhttp是一个封装URL,比HttpClient更友好易用的工具。目前似乎okhttp更流行一些。
官网:http://square.github.io/okhttp/

okhttp.png

RestTemplate底层默认使用的jdk的标准实现,如果我们想让RestTemplate的底层使用okhttp非常简单:
1.添加okhttp依赖

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.9.0</version>
</dependency>

2.设置requestFactory

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}

测试结果与之前一样。

3.4、解决订单系统中的url硬编码问题

通过以上的测试我们发现,在订单系统中要调用商品微服务中的查询接口来获取数据,在订单微服务中将url硬编码到代码中,这样显然不好,因为,运行环境一旦发生变化这个url地址将不可用。

解决方案:将url地址写入到application.properties配置文件中。
实现:修改appcation.properties文件:

appcation.properties.png

修改ItemService中的实现:
ItemService.png

Spring Cloud—一、微服务架构
Spring Cloud—二、Spring Cloud简介
Spring Cloud—三、使用Spring Cloud实现微服务
Spring Cloud—四、Spring Cloud快速入门
Spring Cloud—五、注册中心Eureka
Spring Cloud—六、使用Ribbon实现负载均衡
Spring Cloud—七、容错保护:Hystrix
Spring Cloud—八、使用Feign实现声明式的Rest调用
Spring Cloud—九、服务网关Spring Cloud Zuul
Spring Cloud—十、使用Spring Cloud Config统一管理微服务
Spring Cloud—十一、使用Spring Cloud Bus(消息总线)实现自动更新

demo源码

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,497评论 18 139
  • 前言 现在研发的项目启动今已近一年之久,期间从项目属性、人员规模、系统定位等方面都发生了很大的变化,而且是越变越好...
    孙振强阅读 12,269评论 1 58
  • 摘要:本文中,我们将进一步理解微服务架构的核心要点和实现原理,为读者的实践提供微服务的设计模式,以期让微服务在读者...
    Java架构师Carl阅读 5,738评论 0 20
  • 本文来自作者 未闻 在 GitChat 分享的{基于 Docker 的微服务架构实践} 前言 基于 Docker ...
    AI乔治阅读 7,222评论 0 71
  • 我常想 我爱我自己 这句话让我觉得有点恶心 我不爱其他人 我不爱这个世界 广告狂人始终只是一部剧 对于我爱的大张伟...
    birdree阅读 132评论 0 0