Spring cloud实战 从零开始一个简单搜索网站_Hystrix断路由的实现(三)

news/2024/5/12 1:29:26/文章来源:https://blog.csdn.net/weixin_30617797/article/details/98970629

上文已经完成了一个简单的   浏览器 到 Client 到CSDN端的通路

我们的架构是每个博客网址为一个单独的组件, 这里为了方便直接先用CSDN 那个组件复制下

我这里改成 SDN 修改下 application.properties   端口记得改

eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
spring.application.name=sdn
server.port=8983

 

下面是TOMCAT   和 eureka server运行的截图

 

好了 有两个搜索端了,我这里把CSDN  SDN 叫做搜索端了 , 下面修改下 Client端  让他能分别调用2个组件


我修改了下github上的配置  把我们新建的serviceID加入进去

 

我们会回到Client项目的  ClientService 多了个SDN,需要修改下代码,能让程序自动加载多个HOST(这里只是简单介绍,如果搜索端好几个肯定得改进)

@Service
public class ClientService {@Autowired RestTemplate restTemplate;@Autowiredprivate EurekaClient discoveryClient;@Value("${serviceIds}")public String serviceIds;public String  search(String key,String page) {StringBuffer sb =new StringBuffer();if(serviceIds.contains(",")) {String[] ids = serviceIds.split(",");for(int i=0;i<ids.length;i++) {sb.append(searchDetail(key, page, ids[i]));}}else {sb.append(searchDetail(key, page,serviceIds));}return sb.toString();}public String  searchDetail(String key,String page,String serviceId) {HashMap<String, String> map = new HashMap<>();map.put("key", key);map.put("page", page);String str= restTemplate.getForObject(serviceUrl(serviceId)+"/search?key={key}&page={page}",String.class,map);return str;}@BeanRestTemplate restTemplate() {return new RestTemplate();}public String serviceUrl(String serviceId) {InstanceInfo instance = discoveryClient.getNextServerFromEureka(serviceId, false);return instance.getHomePageUrl();}
}

 

因为数据比较多  我把两个搜索端直接改成返回一个字符串了

@RestController
public class CsdnController {Gson gson = new Gson();@RequestMapping(value = "/search")public String search(@RequestParam("key") String key, @RequestParam("page") String page) {System.out.println("search");ArrayList<HashMap<String, String>> result;try {
//            result = SearchUtil.search(key, "blog", page);
//            return gson.toJson(result);return "i am csdn 1";} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}
}
View Code
public class CsdnController {Gson gson = new Gson();@RequestMapping(value = "/search")public String search(@RequestParam("key") String key, @RequestParam("page") String page) {System.out.println("search");ArrayList<HashMap<String, String>> result;try {
//            result = SearchUtil.search(key, "blog", page);
//            return gson.toJson(result);return "i am sdn 1";} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}
}
View Code

 

这下有两个端了,搜索时间也延长了2倍, 但万一个端有异常  另外一个端良好 怎么办 这时候就需要断路由 hystrix 

 

 在client pom里面导入下 

            <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>

POM 代码

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>tsearch_web</groupId><artifactId>springtest-client</artifactId><version>0.0.1</version><packaging>jar</packaging><name>springtest-client</name><description>Note Server catch</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.1.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><spring-cloud.version>Greenwich.M3</spring-cloud.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-config</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Finchley.RELEASE</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build><repositories><repository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url><snapshots><enabled>false</enabled></snapshots></repository></repositories></project>
View Code

修改下application

@EnableEurekaClient
@SpringBootApplication
@EnableCircuitBreaker
public class SpringtestClientApplication {public static void main(String[] args) {SpringApplication.run(SpringtestClientApplication.class, args);}
}

 

新增个SearchUtil 类

@Component
public class SearchUtil  { @AutowiredRestTemplate restTemplate;@Autowiredprivate EurekaClient discoveryClient;@HystrixCommand(groupKey = "searchDetail1", commandKey = "searchDetail1",fallbackMethod = "stubMyService")public String searchDetail1(String key, String page, String serviceId) {System.out.println("come="+serviceId);HashMap<String, String> map = new HashMap<>();map.put("key", key);map.put("page", page);String str = restTemplate.getForObject(serviceUrl(serviceId) + "/search?key={key}&page={page}", String.class,map);return str;}@HystrixCommand(groupKey = "searchDetail2", commandKey = "searchDetail2",fallbackMethod = "stubMyService")public String searchDetail2(String key, String page, String serviceId) {System.out.println("come="+serviceId);HashMap<String, String> map = new HashMap<>();map.put("key", key);map.put("page", page);String str = restTemplate.getForObject(serviceUrl(serviceId) + "/search?key={key}&page={page}", String.class,map);return str;}public String stubMyService(String key, String page, String serviceId) {return "error";}@BeanRestTemplate restTemplate() {return new RestTemplate();}public String serviceUrl(String serviceId) {InstanceInfo instance = discoveryClient.getNextServerFromEureka(serviceId, false);return instance.getHomePageUrl();}
}
View Code

修改下 ClientService 

@Service
public class ClientService {@AutowiredSearchUtil sc;@Value("${serviceIds}")public String serviceIds;public String search(String key, String page) {StringBuffer sb = new StringBuffer();if (serviceIds.contains(",")) {String[] ids = serviceIds.split(",");sb.append(sc.searchDetail1(key, page, ids[0]));sb.append(sc.searchDetail2(key, page, ids[1]));}else {sb.append(sc.searchDetail1(key, page, serviceIds));}return sb.toString();}}

不断刷新 浏览器 好像没啥区别

给CSDN的Client加个超载

@RestController
public class CsdnController {Gson gson = new Gson();@RequestMapping(value = "/search")public String search(@RequestParam("key") String key, @RequestParam("page") String page) {System.out.println("search");ArrayList<HashMap<String, String>> result;try {
//            result = SearchUtil.search(key, "blog", page);
//            return gson.toJson(result);Thread.sleep(5000);return "i am csdn 1";} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}
}
View Code

继续刷新

然后看下控制台   不是说好的垄断吗  为啥 还是进来了 虽然时间减少了

用Hystrix的时候要注意一点  Hystrix的 超时时间一点要大于resttemplete  或者你用 ribbon   

Hystrix 的默认值全在  com.netflix.hystrix.HystrixCommandProperties

这个就是出错次数 private static final Integer default_circuitBreakerRequestVolumeThreshold = 20;// default => statisticalWindowVolumeThreshold: 20 requests in 10 seconds must occur before statistics matter

我们改下 SearchUtil

@Component
public class SearchUtil  { @AutowiredRestTemplate restTemplate;@Autowiredprivate EurekaClient discoveryClient;@HystrixCommand(groupKey = "searchDetail1", commandKey = "searchDetail1",fallbackMethod = "stubMyService",commandProperties = {@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "5")})public String searchDetail1(String key, String page, String serviceId) {System.out.println("come="+serviceId);HashMap<String, String> map = new HashMap<>();map.put("key", key);map.put("page", page);String str = restTemplate.getForObject(serviceUrl(serviceId) + "/search?key={key}&page={page}", String.class,map);return str;}@HystrixCommand(groupKey = "searchDetail2", commandKey = "searchDetail2",fallbackMethod = "stubMyService")public String searchDetail2(String key, String page, String serviceId) {System.out.println("come="+serviceId);HashMap<String, String> map = new HashMap<>();map.put("key", key);map.put("page", page);String str = restTemplate.getForObject(serviceUrl(serviceId) + "/search?key={key}&page={page}", String.class,map);return str;}public String stubMyService(String key, String page, String serviceId) {return "error";}@BeanRestTemplate restTemplate() {return new RestTemplate();}public String serviceUrl(String serviceId) {InstanceInfo instance = discoveryClient.getNextServerFromEureka(serviceId, false);return instance.getHomePageUrl();}
}
View Code

重启下 不断刷新浏览器    发现 searchDetail1方法不执行了  好了  垄断完成 

 

 

我们需要知道组件的当前状态  这时候就需要hystrix的dashbox

POM 中引入

    <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId></dependency>
View Code

修改下ClientApplication 加入dashboard注释

@EnableEurekaClient
@SpringBootApplication
@EnableCircuitBreaker
@EnableHystrixDashboard
public class SpringtestClientApplication {public static void main(String[] args) {SpringApplication.run(SpringtestClientApplication.class, args);}@Beanpublic ServletRegistrationBean getServlet() {HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);registrationBean.setLoadOnStartup(1);registrationBean.addUrlMappings("/hystrix.stream");registrationBean.setName("HystrixMetricsStreamServlet");return registrationBean;}
}

在浏览器输入http://localhost:8881/hystrix 就能看到界面

 

按上面的填写好  点击Monitor Stream就能进入统计页面

写个函数拼命跑 会发现数字多有变化 鼠标放上去可以看到具体说明

public class TestHystic {public static void main(String[]  args) {long time1=System.currentTimeMillis();String b ="";System.out.println(b.length());for(int i=0;i<100;i++) {try {getData();System.out.println("usertime="+(System.currentTimeMillis()-time1));time1=System.currentTimeMillis();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public static  void  getData() throws Exception {URL serverUrl = new URL("http://localhost:8881/search?key=spring&page=1");HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();InputStream in = conn.getInputStream();BufferedReader br =new BufferedReader(new InputStreamReader(in, "UTF-8"));StringBuffer sb= new StringBuffer();String line;while((line=br.readLine())!=null) {sb.append(line);}System.out.println(sb.toString());in.close();}
}
View Code

 

转载于:https://www.cnblogs.com/dikeboy/p/10060569.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_754989.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

直面春招!java相关技术网站

面试进大厂必问知识点内容 细节见真知:计算向数据移动、而非数据向计算移动 redis的5大Value类型解析 redis实现活跃用户/用户统计 redis实现秒杀/抢购 redis实现排行榜/评论列表 redis实现推荐系统/抽奖/商品详情页 linux系统的支持: fork、 copy on write redis的持久…

看完全都会了!java语言程序设计与数据结构配套网站

微服务是什么 微服务起源于2005年Peter Rodgers博士在云端运算博览会提出的微Web服务(Micro-Web-Service)&#xff0c;根本思想类似于Unix的管道设计理念。2014年&#xff0c;由Martin Fowler 与 James Lewis共同提出了微服务的概念&#xff0c;定义了微服务架构风格是一种通过…

JEECG-P3首个开源插件诞生!CMS网站插件 Jeecg-p3-biz-cms1.0版本发布!

为什么80%的码农都做不了架构师&#xff1f;>>> Jeecg-P3-Biz-Cms &#xff08; JEECG 首个微服务插件&#xff0c;支持小程序的CMS系统&#xff09; 是基于JEECG-P3 微服务框架开发的CMS建站系统&#xff0c;可轻量级集成进jeecg系统&#xff0c;定制各类网站模…

【必看】分析各大招聘网站

目前市场上的招聘网站鱼龙混杂&#xff0c;人力资源市场这块大蛋糕谁都想分一块。工作对于每个人来说都是人生中的一件大事&#xff0c;所以如何选择一个适合自己的经验水平等各方面的正规招聘网站就显得尤为重要&#xff0c;那么今天小编就从客观角度&#xff0c;为大家分析市…

一个基于 SpringBoot 开源的小说和漫画在线阅读网站,简洁大方 !强烈推荐 !...

点击上方“Java基基”&#xff0c;选择“设为星标”做积极的人&#xff0c;而不是积极废人&#xff01;源码精品专栏 原创 | Java 2020 超神之路&#xff0c;很肝~中文详细注释的开源项目RPC 框架 Dubbo 源码解析网络应用框架 Netty 源码解析消息中间件 RocketMQ 源码解析数据库…

解决.net网站打开出现编译器错误消息: CS0016: 未能写入输出文件问题

今天魅力网络在win2008上搭建一个wap的网站程序是asp.net的&#xff0c;发现打开后无法显示&#xff0c;asp的网站可以打开&#xff0c;但asp.net的还是打不开&#xff0c;点基本设置那测试权限了通过了照样打不开&#xff0c;iis的asp.net组件都已经安装了啊&#xff0c;为什么…

IIS安装网站安装发布流程

1.安装IIS打开控制面板---程序和功能选择启用或关闭Windows功能2. 注册IIS因为我们是先安装的VS&#xff0c;后安装的IIS&#xff0c;所以需要将IIS注册进VS中&#xff0c;具体方法如下&#xff1a;在运行中输入“cmd”,回车进入Dos界面上面命令的意思是进入到C:\Windows\Micro…

如何快速实现一个基于Nginx网站的监控场景

一切从应用服务监控说起 小明所在的一家小型互联网创业公司一直将应用运行在阿里云上。该应用采用通用的分布式 NginxApp 架构为用户提供电商数据统计的 webservice 服务。应用运行至今除偶发各类 Bug&#xff0c;性能问题以外&#xff0c;情况还算良好。 undefined 最近&#…

【转载】如何查看自己网站的搜索引擎收录量和索引量

针对于个人站长或者企业站长而言&#xff0c;一般都非常关注自己网站的收录情况以及索引量信息&#xff0c;针对于新上线的网站&#xff0c;搜索引擎一般都还会给予新站保护期进行保护。其实如果要查看自己网站的收录量以及索引量等&#xff0c;可以注册百度站长平台、搜狗站长…

【转载】通过百度站长平台查看网站搜索流量及关键字

无论是个人站还是企业站&#xff0c;都希望网站内容丰富后&#xff0c;网上用户可以通过搜索引擎搜索到网站的内容信息&#xff0c;其实如果站长已经入住了百度站长平台&#xff0c;则我们可以通过百度站长平台的数据监控功能中的查看流量和关键词的菜单来查看具体多少用户通过…

【转载】通过搜狗站长平台查看网站的搜狗流量及搜索关键字

无论是个人站还是企业站&#xff0c;都希望网站内容丰富后&#xff0c;网上用户可以通过搜索引擎搜索到网站的内容信息&#xff0c;其实如果站长已经入住了搜狗站长平台&#xff0c;则可以通过搜狗站长平台的数据监控功能中的查看流量和关键词的菜单来查看具体多少用户通过搜狗…

【转载】通过搜狗站长平台提交网站域名变更后的文章地址

在实际的网站运维过程中&#xff0c;有时候可能会进行网站域名信息的变更&#xff0c;将一个网站的内容全部迁移到另一个域名下&#xff0c;之前的网站域名作废的情况&#xff0c;如果网站收录量不多&#xff0c;直接迁移即可&#xff0c;如果网站收录量很多&#xff0c;则可能…

【转载】通过百度站长平台提交网站死链

运维过网站的人员都知道&#xff0c;网站在运维过程中&#xff0c;因为各种原因如文章删除、网站改版等原因会产生一些失效的网页链接&#xff0c;即我们通常所说的死链&#xff0c;如果死链过多&#xff0c;可能会影响到搜索引擎对我们网站质量权重的判定以及造成不好的用户体…

Redis升级到 6.x 版本后,12306网站起飞了!

提起业务量&#xff0c;除了京东618&#xff0c;淘宝双11&#xff0c;当数全民抢票平台 12306最有发言权。后台有位粉丝问了个很典型的问题&#xff0c;同样是架设在阿里云上的服务器&#xff0c;为什么12306经常会宕机&#xff0c;而双11阿里每秒钟50多万笔订单&#xff0c;都…

获取了网站源码有什么用_环保做推广用什么平台_广告投放-多网站信息推广

环保做推广用什么平台_广告投放-多网站信息推广 讯呱呱(深圳)网络科技有限公司成立于2020-06-18&#xff0c;法定代表人为刘宪玲&#xff0c;注册资本为101万元&#xff0c;统一社会信用代码为91440300MA5G8KKX6D。企业地址位于深圳市龙华区龙华街道清华社区和平路64号中国振华…

怎样获取网站的域名_网站如何被百度收录?

百度搜索引擎对网站的收录与很多方面的因素有关&#xff0c;网站如果想要得到百度搜索引擎收录的话&#xff0c;站长需要不断对网站的整体结构进行调整和完善&#xff0c;从网站结构、内容、链接等细节方面着手优化&#xff0c;才能突破收录困境&#xff0c;循序渐进的提升网站…

教你用 docker 搞个网站

点击上方“Java基基”&#xff0c;选择“设为星标”做积极的人&#xff0c;而不是积极废人&#xff01;每天 14:00 更新文章&#xff0c;每天掉亿点点头发...源码精品专栏 原创 | Java 2021 超神之路&#xff0c;很肝~中文详细注释的开源项目RPC 框架 Dubbo 源码解析网络应用框…

web文件 群晖_群晖NAS安装wordpress博客,构建属于自己的web网站

学习网络技术的话可以关注我&#xff0c;每天都会有相应的教程发布的&#xff01;群晖NAS主要的作用就是网络储存&#xff0c;你可以理解为百度云&#xff0c;但这个百度云的服务器放在了家里。个人而言&#xff0c;有了NAS以后&#xff0c;家里的所有设备(台式电脑&#xff0c…

# 解析bt文件_一键查看BT下载记录,用这网站一秒知道你下载过哪些资源

既然刷到了&#xff0c;就收藏起来吧&#xff01;以备不时之需&#xff01;想要知道自己过去用BT或磁力链下载过哪些电影、游戏或软件等资源吗&#xff1f;你可能还不知道&#xff0c;其实在 BT 下载时&#xff0c;自己的 IP 位置就已经被记录&#xff0c;通过「iknowwhatyoudo…

html网页主题有哪些,网站的专题页面是什么?

做SEO的时候&#xff0c;很多时候一个权重高的网站做久了&#xff0c;就会有很多的权重排名高的目标关键词和长尾关键词排获取不错的流量。但是有一些关键词热度较高&#xff0c;而普通的文章因为多数是采用模板输出所以页面权重较低&#xff0c;导致在竞争中排名不靠前。而这时…