Spring Cloud—三芭毙、使用Spring Cloud實現(xiàn)微服務(wù)

業(yè)務(wù):
1.商品微服務(wù):通過商品id查詢商品的服務(wù)筋蓖。
2.訂單微服務(wù):創(chuàng)建訂單時,通過調(diào)用商品的微服務(wù)進行查詢商品數(shù)據(jù)稿蹲。

業(yè)務(wù).png

說明:
1.對于商品微服務(wù)而言扭勉,商品微服務(wù)是服務(wù)的提供者,訂單微服務(wù)是服務(wù)的消費者苛聘。
2.對于訂單微服務(wù)而言涂炎,訂單微服務(wù)是服務(wù)的提供者忠聚,人是服務(wù)的消費者。

3.1唱捣、實現(xiàn)商品微服務(wù)

3.1.1两蟀、創(chuàng)建工程
創(chuàng)建工程.png
3.1.2、導(dǎo)入依賴
<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震缭、創(chuàng)建實體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用于實現(xiàn)具體的商品查詢邏輯,為了方便拣宰,我們并不真正的連接數(shù)據(jù)庫党涕,而是做模擬實現(xiàn)。

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;

    /**
    * 對外提供接口服務(wù)膛堤,查詢商品信息
    */
    @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格式的文件是相互轉(zhuǎn)化的。如:

Server:
    prot:18100

等價于

server.port=18100

配置文件的示例:
application.properties.png
3.1.7谭期、啟動程序測試
測試結(jié)果.png

3.2堵第、實現(xiàn)訂單微服務(wù)

3.2.1、創(chuàng)建工程springcloud-demo-order (同3.1.1)
3.2.2隧出、導(dǎo)入依賴 (同3.1.2)
3.2.3、創(chuàng)建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阀捅、創(chuàng)建訂單詳情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胀瞪、將商品微服務(wù)中的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實現(xiàn)的根據(jù)訂單Id查詢訂單的服務(wù)凄诞,為了方便測試,我們將構(gòu)造數(shù)據(jù)實現(xiàn)忍级,不采用查詢數(shù)據(jù)庫的方式帆谍。

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;

    /**
    * 根據(jù)訂單id查詢訂單數(shù)據(jù)
    */
    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烈涮、啟動測試
測試結(jié)果.png

3.3、添加okHttp的支持

okhttp是一個封裝URL窖剑,比HttpClient更友好易用的工具坚洽。目前似乎okhttp更流行一些。
官網(wǎng):http://square.github.io/okhttp/

okhttp.png

RestTemplate底層默認使用的jdk的標準實現(xiàn)西土,如果我們想讓RestTemplate的底層使用okhttp非常簡單:
1.添加okhttp依賴

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

2.設(shè)置requestFactory

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

測試結(jié)果與之前一樣讶舰。

3.4、解決訂單系統(tǒng)中的url硬編碼問題

通過以上的測試我們發(fā)現(xiàn)需了,在訂單系統(tǒng)中要調(diào)用商品微服務(wù)中的查詢接口來獲取數(shù)據(jù)跳昼,在訂單微服務(wù)中將url硬編碼到代碼中,這樣顯然不好肋乍,因為鹅颊,運行環(huán)境一旦發(fā)生變化這個url地址將不可用。

解決方案:將url地址寫入到application.properties配置文件中住拭。
實現(xiàn):修改appcation.properties文件:

appcation.properties.png

修改ItemService中的實現(xiàn):
ItemService.png

Spring Cloud—一挪略、微服務(wù)架構(gòu)
Spring Cloud—二、Spring Cloud簡介
Spring Cloud—三滔岳、使用Spring Cloud實現(xiàn)微服務(wù)
Spring Cloud—四杠娱、Spring Cloud快速入門
Spring Cloud—五、注冊中心Eureka
Spring Cloud—六谱煤、使用Ribbon實現(xiàn)負載均衡
Spring Cloud—七摊求、容錯保護:Hystrix
Spring Cloud—八、使用Feign實現(xiàn)聲明式的Rest調(diào)用
Spring Cloud—九刘离、服務(wù)網(wǎng)關(guān)Spring Cloud Zuul
Spring Cloud—十室叉、使用Spring Cloud Config統(tǒng)一管理微服務(wù)
Spring Cloud—十一、使用Spring Cloud Bus(消息總線)實現(xiàn)自動更新

demo源碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末硫惕,一起剝皮案震驚了整個濱河市茧痕,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌恼除,老刑警劉巖踪旷,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異豁辉,居然都是意外死亡令野,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進店門徽级,熙熙樓的掌柜王于貴愁眉苦臉地迎上來气破,“玉大人,你說我怎么就攤上這事餐抢∠质梗” “怎么了低匙?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長朴下。 經(jīng)常有香客問我努咐,道長,這世上最難降的妖魔是什么殴胧? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任渗稍,我火速辦了婚禮,結(jié)果婚禮上团滥,老公的妹妹穿的比我還像新娘竿屹。我一直安慰自己,他們只是感情好灸姊,可當我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布拱燃。 她就那樣靜靜地躺著,像睡著了一般力惯。 火紅的嫁衣襯著肌膚如雪碗誉。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天父晶,我揣著相機與錄音哮缺,去河邊找鬼。 笑死甲喝,一個胖子當著我的面吹牛尝苇,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播埠胖,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼糠溜,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了直撤?” 一聲冷哼從身側(cè)響起非竿,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎谋竖,沒想到半個月后汽馋,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡圈盔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了悄雅。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片驱敲。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖宽闲,靈堂內(nèi)的尸體忽然破棺而出众眨,到底是詐尸還是另有隱情握牧,我是刑警寧澤,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布娩梨,位于F島的核電站沿腰,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏狈定。R本人自食惡果不足惜颂龙,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望纽什。 院中可真熱鬧措嵌,春花似錦、人聲如沸芦缰。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽让蕾。三九已至浪规,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間探孝,已是汗流浹背笋婿。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留再姑,地道東北人萌抵。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像元镀,于是被迫代替她去往敵國和親绍填。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,871評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理栖疑,服務(wù)發(fā)現(xiàn)讨永,斷路器,智...
    卡卡羅2017閱讀 134,656評論 18 139
  • 前言 現(xiàn)在研發(fā)的項目啟動今已近一年之久遇革,期間從項目屬性卿闹、人員規(guī)模、系統(tǒng)定位等方面都發(fā)生了很大的變化萝快,而且是越變越好...
    孫振強閱讀 12,296評論 1 58
  • 摘要:本文中锻霎,我們將進一步理解微服務(wù)架構(gòu)的核心要點和實現(xiàn)原理,為讀者的實踐提供微服務(wù)的設(shè)計模式揪漩,以期讓微服務(wù)在讀者...
    Java架構(gòu)師Carl閱讀 5,779評論 0 20
  • 本文來自作者 未聞 在 GitChat 分享的{基于 Docker 的微服務(wù)架構(gòu)實踐} 前言 基于 Docker ...
    AI喬治閱讀 7,279評論 0 71
  • 我常想 我愛我自己 這句話讓我覺得有點惡心 我不愛其他人 我不愛這個世界 廣告狂人始終只是一部劇 對于我愛的大張偉...
    birdree閱讀 136評論 0 0