- Microservices Development Cookbook
- Paul Osman
- 167字
- 2021-07-16 17:48:27
How to do it...
- Open the service object we created in the previous recipe. We'll modify the service object to be able to call an external microservice responsible for managing attachments. For the sake of simplicity, we'll use an HTTP client that is provided in the Ruby standard library. The service object should be in the app/services/attachments_service.rb file:
class AttachmentsService
BASE_URI = "http://attachment-service.yourorg.example.com/"
def upload(message_id, user_id, file_name, data, media_type)
body = {
user_id: user_id,
file_name: file_name,
data: StringIO.new(Base64.decode64(params[:file]
[:data]), 'rb'),
message: message_id,
media_type: media_type
}.to_json
uri = URI("#{BASE_URI}attachment")
headers = { "Content-Type" => "application/json" }
Net::HTTP.post(uri, body, headers)
end
end
- Open the attachments_controller.rb file, located in pichat/app/controllers/, and look at the following create action. Because of the refactoring work done in the previous chapter, we require only a small change to make the controller work with our new service object:
class AttachmentsController < ApplicationController
# POST /messages/:message_id/attachments
def create
service = AttachmentService.new
response = service.upload(params[:message_id], current_user.id,
params[:file][:name], params[:file][:data],
params[:media_type])
json_response(response.body, response.code)
end
# ...
end
推薦閱讀
- 物聯(lián)網(wǎng)與北斗應(yīng)用
- Twilio Cookbook
- INSTANT PhpStorm Starter
- 重新定義Spring Cloud實(shí)戰(zhàn)
- Django 2 by Example
- 互聯(lián)網(wǎng)安全的40個(gè)智慧洞見(jiàn):2014年中國(guó)互聯(lián)網(wǎng)安全大會(huì)文集
- Building RESTful Web services with Go
- 網(wǎng)絡(luò)設(shè)計(jì)與應(yīng)用(第2版)
- Learning Storm
- 局域網(wǎng)組成實(shí)踐
- Guide to NoSQL with Azure Cosmos DB
- 智能物聯(lián)網(wǎng):區(qū)塊鏈與霧計(jì)算融合應(yīng)用詳解
- 黑客心理學(xué):社會(huì)工程學(xué)原理
- 網(wǎng)絡(luò)互聯(lián)技術(shù)(理論篇)
- 路由與交換技術(shù)