目录
前言
云服务器用起来感觉最难受的就是带宽了,国内的云服务器普遍带宽都很小,但买国外或者香港的话延迟大还容易被封IP。一般网站/app最占带宽的是图片和音视频等文件的上传下载,下面我们要聊的cos和cdn就是解决这个问题来的。
简介
对象存储COS
- 对象存储不同于我们平时操作系统里的文件存储,它就像一个map,存储的所有文件都有一个唯一的名称作为key,文件内容作为value。而没有目录的概念。
- 这样做的意义在于,当文件很多,目录结构深时,文件存储需要根据那颗目录树一步一步找到文件,显然是比对象存储直接按文件名一步到位得到要来得慢。
- 但目前很多云服务厂商都有在对象存储上提供目录功能,这大多是模拟出来的。比如腾讯云是将文件名中的 / 识别为目录模拟得到的。
- 比如:放进两个文件:
- aaa.txt
- wow/abc.cpp
- 由于 "wow/abc.cpp" 的文件名带有 / ,则可以模拟解析为是放在wow目录下,存在一个文件叫abc.cpp。
- 我们使用云服务提供的COS来替换我们的服务器实现文件的上传和下载。一般云服务COS不限制下载速度,且用户上传也免费。但用户的下载流量、存储空间占用、请求次数是要收钱的。
- 注意这不是三选一的问题,是三个方面都要收钱的!
- 比如:在一个月的时间里,我们向COS上传了 100 MB 文件,发送过 1 w 次读写请求,且用户外网下载文件使用过 10G 的流量。
- 那么结算时,需要支付:A + B + C
- A:100M/1个月 的存储空间占用费用
- B:1w次读取请求费用
- C:外网下载 10 G 流量费用
- 显然,外网下载流量很容易被人攻击,盗刷流量,然后疯狂扣流量包扣费,容易出现一觉醒来,没了一套海景房的刺激。后面我们用CDN来防止一部分攻击,因为COS的流量费比CDN贵非常多,而且CDN能设置更多的访问限制,降低被攻击的损失,所以可以用CDN抗在前面。
CDN
- cdn的用途很广泛,由于用户在地域上分布全国甚至全球各地,而我们的服务器一般是只在一个或几个地方而已,cdn在地域上可以分散多个节点,作为一个中间人,缓存用户访问服务器上的文件,并在用户下一次请求这个文件时,cdn就可以直接提供给用户,而不需要大老远来请求服务器,提高用户的访问速度。
- 这里我们可以利用这个特性,且其价格低,来帮助COS降低被攻击的损失。
使用问题
盗刷COS流量
- 前面我们已经提到,COS的外网下载流量是比较贵的,而且速度快,容易被攻击刷流量。
- 解决办法:
- 把COS访问权限设置为 私有读私有写
- 当用户需要上传文件时,使用云厂商提供的SDK,服务端预签名上传文件的URL,并将签名后的链接发送给用户,客户端只能按照签名链接指定参数、请求头、请求类型的上传文件到COS,上传不需要使用CDN。
- 当用户需要下载时,使用SDK获取COS上对应文件名的文件链接,并将链接的域名替换为CDN的域名,然后返回替换后的链接给用户下载文件,并在CDN设置限制IP访问速度、下载速度等限制即可。
防盗链/限速
- 由于浏览器不允许伪造请求头中的Referer、Host、Origin,因此可以在CDN/COS都配置防盗链,限制请求的Referer。这个可以阻止别人的网站直接把你的资源链接放到他的网站使用的情况,减少一些被偷资源流量的问题,但他直接下载你的资源然后上传到他的服务器还是可以的。
- 注意网页是可以指定浏览器不携带Referer的,即请求是空Referer。而在浏览器直接敲网址进入网页时的请求也是空Referer,你需要考虑是否需要允许空Referer的请求。防盗链挡不住客户端请求,因为客户端是可以随意伪造请求中的任意值的。如APP、nodejs、命令行、服务端程序等,只要是非标准浏览器环境就可以随意伪造。
- 在CDN中,可以限制下载速度、IP访问速度等。
https网站中使用http资源
- 由于CDN的Https目前很多云厂商是收费的,虽然不贵,但也是钱。
- 如果你CDN访问使用了http,但网站是https协议时,直接在https网站里获取http资源(图片、音视频等)会被浏览器认为是不安全的,并在浏览器的开发者工具中打印警告,但也是能用的。但默认不会带上Referer,因此如果你设置了防盗链不允许空Referer的话,就有问题了,这个时候可以在网页的<head></head>中添加配置:<meta content="always" name="referrer" >,这样浏览器在获取Http资源时也会带上Referer了
- https网站中发起http请求是不允许的!
上传文件大小/数量限制
- 用户向我们的服务端申请用于上传文件的预签名URL时,需要携带参数:文件大小、文件MD5,然后我们可以指定该链接发送时必须携带:
- Content-Length=500
- x-cos-meta-md5: {文件md5值}
- 由此就可以防止用户拿到预签名URL后,上传了其他文件的问题
- 文件大小限制,就是在我们服务端给预签名URL时进行检查。
- 文件数量限制,可以将用户、IP获取上传链接时写入数据库记录,根据这个记录来设计用户上传文件的数量和总大小等。
腾讯云COS的SDK/c++
- 整了老半天,终于写好了cmakelist能编译运行release,但debug版一直找不到链接符号。
- 看了大概是因为他是SDK源码里有一个文件夹three-party存放了已经编译好的第三方依赖库,但这些库是release的,因此需要我们编译debug的依赖库。但我的项目里也依赖openssl,改来改去才能release,最终debug版放弃了。
- 后来开始用上go了,学1天然后上手引入他的sdk和框架开发完cos相关的接口。有c基础还是很快上手的。
I was recommended this blog by my cousin. I’m not sure whether
this post is written by him as no one else know such detailed about my
problem. You are amazing! Thanks!
https://mexicanpharmacy1st.shop/# pharmacies in mexico that ship to usa
Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across.Seo Paketi Skype: By_uMuT@KRaLBenim.Com -_- live:by_umut
werankcities.com
그녀는 실제로 소녀이고 Tiger의 책을 읽는 소녀가 있다고 생각하지 않았습니다.그는 실제로 이때 침수 지역의 모든 사람들을 재배치하기로 결정했습니다.
I really love to read such an excellent article. Helpful article. Hello Administ . Seo Paketi Skype: By_uMuT@KRaLBenim.Com -_- live:by_umut
Mscherrybomb provides in-depth journalism and insight into the most impactful news and trends shaping the trucking industry. https://mscherrybomb.com/
medication from mexico pharmacy: mexican mail order pharmacies – buying from online mexican pharmacy
Your writing style is both engaging and informative.대출
Автор 24 – это высококачественный сервис для заказа разнообразных академических работ. Он специализируется на дипломных работах, а также чертежах. Кроме того, на сервисе Автор 24 можно купить эссе, презентации. Это эффективный способ получить профессиональную помощь.
Автор 24 Автор 24 .
Сервис Автор 24 – это превосходный сервис для приобретения различных академических работ. Он специализируется на курсовых работах, а также задачах. Кроме того, на Автор 24 можно заказать эссе, отчеты о прохождении практики. Это эффективный способ сэкономить время.
Автор 24 ру Автор 24 официальный .
https://mexicanpharmacy1st.online/# mexican online pharmacies prescription drugs
Small Oiling ? One of many vital enhancements around TPE would be the オナホ 高級considerably minimized oil secretion, creating servicing simpler plus much more handy.
best online pharmacies in mexico: mexican border pharmacies shipping to usa – best online pharmacies in mexico
https://www.sostav.ru/blogs2/260771/45805
“Everybody wants to be famous, but nobody wants to do the work. I live by that. You grind hard so you can play hard. At the end of the day, you put all the work in, and eventually it’ll pay off. It could be in a year, it could be in 30 years. Eventually, your hard work will pay off.” 사설토토추천
Woah! I’m really digging the template/theme of this site.
It’s simple, yet effective. A lot of times it’s challenging to
get that “perfect balance” between user friendliness and visual appeal.
I must say you’ve done a amazing job with this.
Additionally, the blog loads super quick for me on Opera.
Outstanding Blog!
After all, what a great site and informative posts, I will upload inbound link – bookmark this web site? Regards, Reader.Seo Paketi Skype: By_uMuT@KRaLBenim.Com -_- live:by_umut
https://mexicanpharmacy1st.online/# medication from mexico pharmacy
Susibu provides in-depth journalism and insight into the news and trends impacting the hotel https://susibu.com/
I strongly recommend stay away from this platform. My own encounter with it was only dismay and concerns regarding scamming practices. Proceed with extreme caution, or better yet, seek out an honest service for your needs.
mexican drugstore online best online pharmacies in mexico п»їbest mexican online pharmacies
purple pharmacy mexico price list: mexican rx online – purple pharmacy mexico price list
I urge you to avoid this platform. The experience I had with it was purely frustration and doubts about fraudulent activities. Exercise extreme caution, or alternatively, look for an honest service to meet your needs.
Thank you for great article. Hello Administ .Seo Paketi Skype: By_uMuT@KRaLBenim.Com -_- live:by_umut
If you choose “isn’t going to issue”,オナホ 高級 We are going to make your mind up along with the company corresponding with availability.
We have now some fascinating information that we can’t wait to share with you! To be a valued member オナホ 高級of our Neighborhood,
reputable mexican pharmacies online: mexican rx online – buying from online mexican pharmacy
I highly advise to avoid this platform. My personal experience with it was purely frustration along with suspicion of scamming practices. Proceed with extreme caution, or even better, seek out a trustworthy service to fulfill your requirements.
Привет всем!
Как заказать и купить диплом Вуза недорого без предоплаты на сайте? Доставка в любую точку России
http://www.diplomany-asx.ru
if you want get a cheaper for getting begin your fantastic sexlife with dolls,オナホ 高級 Then TPE doll will be Excellent selection for you.
I urge you steer clear of this site. The experience I had with it has been purely frustration and concerns regarding scamming practices. Be extremely cautious, or alternatively, find a trustworthy service to fulfill your requirements.
merhaba admin siteniz çok güzel
mexican rx online: buying prescription drugs in mexico – reputable mexican pharmacies online
В современном мире, где диплом – это начало успешной карьеры в любой отрасли, многие ищут максимально быстрый путь получения образования. Факт наличия документа об образовании трудно переоценить. Ведь диплом открывает дверь перед людьми, стремящимися вступить в сообщество профессиональных специалистов или учиться в ВУЗе.
В данном контексте наша компания предлагает максимально быстро получить этот важный документ. Вы можете заказать диплом старого или нового образца, что является отличным решением для всех, кто не смог закончить обучение или утратил документ. Все дипломы изготавливаются с особой тщательностью, вниманием ко всем нюансам, чтобы в итоге получился продукт, 100% соответствующий оригиналу.
Плюсы подобного решения заключаются не только в том, что можно оперативно получить диплом. Весь процесс организован просто и легко, с профессиональной поддержкой. Начав от выбора необходимого образца до консультации по заполнению личных данных и доставки в любой регион России — все будет находиться под абсолютным контролем квалифицированных мастеров.
Для всех, кто ищет оперативный способ получить необходимый документ, наша компания готова предложить отличное решение. Купить диплом – это значит избежать длительного обучения и сразу переходить к своим целям, будь то поступление в университет или старт трудовой карьеры.
http://man-attestats24.com
I’m sharing this with my colleagues right away.급전
I highly advise stay away from this platform. My personal experience with it was nothing but dismay along with suspicion of fraudulent activities. Exercise extreme caution, or even better, find a more reputable service for your needs.
bestmanualpolesaw.com
Hongzhi 황제의 마음 깊은 곳에서 그는 이미 분노했습니다.
http://mexicanpharmacy1st.com/# reputable mexican pharmacies online
if you want get a cheaper for getting begin your fantastic sexlife with dolls, オナホ 高級Then TPE doll will be Excellent selection for you
NordinV provides in-depth journalism and insight into the news and trends impacting the fashion
Allnew Boss Dont delete Drastically reduced Exclusive deal
Get it now Get started now Important information regarding
Instant Limited time New customers only Now
only Satisfied free 0 risk 00 1 month ago 18 18 video 31 50 off 100 free 100 more 100 satisfaction 100 satisfied AS
SEEN ON Accept credit cards Acceptance Access Access now Accordingly Act
Act Immediately Act now Act now Dont hesitate Action Required Ad Additional income Addresses Addresses on CD Affordable
All All natural All new Allnatural Amazing Apply Online Apply now Apply
online As As seen on At no cost Auto email removal Avoice bankruptcy Avoid Avoid bankruptcy BUY
BUY DIRECT Bargain Be amazed Be your own boss
Become a member Being a member Beneficiary Best price Big bucks Bill 1618
Billing Billing address Billion Billion dollars Bonus Brand new pager Bulk email Buy Buy direct Buy now Buying judgments CURES BALDNESS Cable converter Call Call free Call
now Calling creditors Cancel Cancel at any time Cannot be combined with any other
offer Cant live without Card accepted Cards accepted Cash Cash bonus Cashcashcash Casino Celebrity Cellphone cancer scam Cents on the dollar
Certified Chance Cheap Cheap meds Check Check or money order Claims Claims not to be selling anything Claims to be legal Claims
you are a winner Clearance Click Click below Click here Click here link Click to remove Click to remove mailto Collect Collect child support Compare Compare rates Compete for your business Confidentiality Confidentially on all orders Congratulations Congratulations Consolidate debt
Consolidate debt and credit Consolidate your debt Copy DVDs Copy accurately Cost Costs Credit Credit bureaus
Credit card offers Cures Cures baldness Cutie DIAGNOSTICS Deal Deal
ending soon Dear emailfriendsomebody Dear personalization variable Dear email Dear friend
Dear somebody Debt Diet Different reply to Dig up dirt on friends Digital marketing
Direct email Direct marketing Discount Discusses search engine listings
Do it now Do it today Dont delete Dont hesitate Dont hesitate Dormant Double your Double your cash
Double your income Drastically reduced Earn Earn Earn cash
Earn extra cash Earn money Earn per week Easy terms Ecommerce Eliminate bad credit Eliminate debt Email harvest Email marketing Exclusive deal Expect to earn Explode your business Extra Extra
cash Extra income Free FAST Fantastic Fantastic deal Fast
Viagra delivery Fast cash Fast money Financial Financial freedom
Financially independent Find out anything For Only For free For instant access For
just some amount For just insert whatever amount For
just XXX For just xxx Form Free Free DVD Free access Free cell phone Free consultation Free gift Free grant money Free
hosting Free info Free installation Free investment Free leads Free
membership Free money Free offer Free preview Free priority mail
Free quote Free sample Free trial Free website Freedom Friend Full refund Get Get it away
Get it now Get it today Get out of debt Get paid
Get rid of debt Get started now Gift certificate Give it away Giveaway Giving away Great offer Growth hormone Guarantee
Guaranteed Have you been turned down Hello Here Hidden Hidden assets Hidden charges Home Home Based business Home based Home employment Homebased Homebased business Hot
babes Hottie Human Human growth hormone Hurry up If only it were
that easy Important information regarding In accordance with laws Income Income from home Increase Income Increase sales Increase traffic Increase your sales Incredible deal
Info you requested Information you requested Instant Instant weight loss Insurance Insurance Lose weight Internet market Internet marketing Investment Investment decision Its effective Join millions Join millions of Americans Join thousands Junk Kinky
Laser printer Leave Legal Life Life insurance Lifetime Limited time Limited time offer Limited time only Loan Loans Long distance phone
offer Lose Lose weight Lose weight spam Lottery Lower
interest rate Lower interest rates Lower monthly payment Lower rates Lower your mortgage
rate Lowest insurance rates Lowest price Luxury Luxury car MLM
Mail in order form Maintained Make Make money Marketing
Marketing solution Marketing solutions Mass email Mature Medical Medicine Medium Meet girls Meet singles Meet
women Member Member stuff Message contains Message contains disclaimer Million Million dollars Miracle Money Money back Money making Month trial offer More Internet Traffic More internet traffic Mortgage Mortgage rates Multi level marketing
Multilevel marketing Name brand Near you Never New New
customers only New domain extensions Nigerian No age restrictions No catch No claim
forms No cost No credit check No disappointment No experience No fees No gimmick No hidden No hidden Costs No hidden costs No hidden fees No interest No inventory No investment No medical exams No medical exams No middleman No obligation No purchase necessary No
purchase required No questions asked No refunds No selling No strings
attached Noobligation Not intended Not junk Notspam Now Now only Obligation Off shore Offer Offer expires Offers coupon Offers extra cash Offers free often stolen passwords Offshore Once in a lifetime Once in lifetime One hundred percent free One hundred percent guaranteed One time One time mailing
Online biz opportunity Online biz opportunity Online business opportunity Online degree Online marketing Online pharmacy Only Open Opportunity Opt
in Order Order now Order shipped by Order status Order today Orders shipped by Orders shipped by priority mail Orders
shipped by shopper Outstanding values Passwords Pennies a day People just
leave money laying around Performance Please read
Potential earnings Preapproved Price Prices Print form signature Print out and fax Priority
mail Prize Prizes Problem Produced and sent out Profits Promise Promise you Promise you Pure Profits Pure profit Quote Quotes Rates Real
thing Refinance Refinance home Refinanced home Removal Removal instructions Remove
Remove in quotes Remove subject Removes wrinkles
Reply remove subject Request Requires initial investment Reserves
the right Reverses Reverses aging Risk free Riskfree Rolex Round the world
S 1618 Safeguard notice Sale Sales Sample Satisfaction Satisfaction guaranteed Save Save big Save big money Save up to Score Score with babes Search engine Search engine listings Search engines Section 301 See for yourself Sent in compliance Serious cash Serious only Sex
Sexy babes Shopping spree Sign up free Sign up free today Social security number Solution Spam Special promotion Stainless steel Steamy Stock alert Stock disclaimer
statement Stock pick Stop Stop snoring Stops snoring Strong
buy Stuff on sale Subject to cash Subject to credit Subject to Subscribe
Success Supplies are limited Take action Take action now Talks about hidden charges Talks about prizes Teen Tells you its an ad Terms and conditions The best rates The following form They
keep your money no refund They keep your money no refund Theyre just giving it away This is an ad This isnt junk This isnt
spam This isnt a scam This isnt junk This isnt spam This wont
last Thousands Trial US dollars Undisclosed Undisclosed recipient
University diplomas Unlimited Unsecured credit Unsecured creditdebt Unsecured debt Unsolicited Unsubscribe Urgent VIAGRA DELIVERY Vacation Vacation offers Valium Valium
Viagra Very Cheap Viagra Viagra and other drugs Vicodin Visit our website Wants credit card Warranty We are legal We hate spam We honor all Web traffic Weekend
getaway Weight loss What are you waiting for While stocks last While
supplies last While you sleep Who really wins Why pay more Will not believe your eyes Win Win big
Winner Winning Won Work at home Work from home XXX Xanax
You are a winner You are a winner You have been selected Your income Youve been selected adrianne animal arms bakire baldız buttocks cannabis child porn cocaine cp
ecstasy erotic erotig erotik eskort etek gizli go url growth hormone haydar hayvan heroin hidden charges
hikaye homosexual hot how to molest how to rape
a man iptal itiraf ketamine kulot laurence
sampson limited time liseli lsd mephedrone
nefes off partner penis enlargement surgery rebbeca
parer sarisin seen on seks sex sex toys sexual enhancers sexual fetish lingerie shawn mchugh sheila shopper
sicak snoring sperm telekz telekız vaginal
laser rejuvenation viagra viagra satın al viagrayı çevrimiçi satın alın viagrayı çevrimiçi satın alındit weight spam wilma melrose xxx yasak yerli yetiskin yetişkin videosu zoo çocuk pornosu çocuk pornosudiz Hidden assets
Доброго всем дня!
Купите диплом ВУЗа по выгодной цене с гарантией качества и доставкой в любой город России без предоплаты – просто и надежно!
https://diplomany-asx.ru/
For those who have been blocked by mistake, you should Make contact with us! Make sure to オナホ 高級include things like your IP address making sure that we are able to whitelist it.
also be more expensive mainly because they happen to be shipped to San Antonioオナホ 高級 very first as opposed to shipping and delivery immediate to the customer from China.
Sinohuiyuan provides in-depth journalism and insight into the news and trends impacting facilities management https://sinohuiyuan.com
Hurrah! At last I got a webpage from where I be capable of genuinely take helpful facts
concerning my study and knowledge.
mexican pharmacy: buying prescription drugs in mexico online – reputable mexican pharmacies online
Привет, дорогой читатель!
Приобретите документы об образовании всех ВУЗов России с гарантированной подлинностью и доставкой по РФ без предварительной оплаты – просто, надежно, выгодно!
http://www.diplomany-asx.ru
Sudaten provides in-depth journalism and insight into the news and trends impacting the energy, sustainability and governance space. https://sudaten.com
We have now some fascinating information that we can’t wait to share with you! To be a valued member オナホ 高級of our Neighborhood,