SpringCloud将现在一些流行的技术整合到一起,实现如:配置管理,服务发现,智能路由,负载均衡,熔断器,控制总线,集群状态等等功能。主要涉及的组件有

netflix

  • Eureka:注册中心

  • Zuul:服务网关

  • Ribbon:负载均衡

  • Feign:服务调用

  • Hystix:熔断器

环境准备:一个数据库和表tb_user

1.创建一个父工程,和子模块consumer-demo,eureka-server,eureka-server2(两个是eureka的高可用性练习),user-server,(user-server2是对user server的集群练习可以不要)zuul-Demo。

(完整代码:https://gitee.com/mountaincold/cloudDemo)

2. 创建注册中心 eureka-server

  1.pom.xml 导入依赖 eureka服务端

  2. 创建启动类 eureka1

  3. 设置application.yml

eureka-server2相同把端口换成10087,注册地址换成10086就行了

2.创建服务提供者userservice

  1. pom.xml的配置 导入依赖

 <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId></dependency><!-- Eureka客户端 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency></dependencies>

  2. 设置application.yml配置文件

server:port: 8081
spring:datasource:url: jdbc:mysql://localhost:3306/mybatisusername: rootpassword: 960326application:name: userservice
logging:level:com.practice:debug
eureka:client:service-url: #eurekaServer 地址defaultZone: http://127.0.0.1:10086/eureka,http://127.0.0.1:10087/eurekainstance:prefer-ip-address: true #当调用getHostname获取实例的hostname时 返回ip而不是host名称ip-address: 127.0.0.1 #指定自己的ip信息 不指定的话会自己寻找lease-expiration-duration-in-seconds: 10 #服务失效时间 默认90秒lease-renewal-interval-in-seconds: 5 #服务续约时间的间隔,默认30秒instance-id: ${spring.application.name}:${server.port} #设置id

  2.创建启动类,和pojo对象类

@Table(name = "tb_user")
public class User implements Serializable {private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;// 用户名private String userName;// 密码private String password;// 姓名private String name;// 年龄private Integer age;// 性别,1男性,2女性private Integer sex;// 出生日期private Date birthday;// 创建时间private Date created;// 更新时间private Date updated;// 备注
//    private String note;// 。。。省略getters和setters//TODO 需要手动添加getter,setter
}

  

  3.创建controller,service ,mapper

package com.practice.controller;import com.practice.pojo.User;
import com.practice.service.UserService;
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.RestController;
import org.springframework.web.bind.annotation.RequestMapping;@RestController
@RequestMapping("user")
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/{id}")public User queryById(@PathVariable("id") Long id) {return this.userService.queryById(id);}
}/**
*设置睡眠是为了测试熔断器
*/
package com.practice.service;import com.practice.mapper.UserMapper;
import com.practice.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class UserService {@Autowiredprivate UserMapper userMapper;private static final Logger logger = LoggerFactory.getLogger(UserService.class);public User queryById(Long id) {Long startTime = System.currentTimeMillis();int time = (int)(Math.random()*2000+1);try {Thread.sleep(time);} catch (InterruptedException e) {e.printStackTrace();}User user = this.userMapper.selectByPrimaryKey(id);Long endTime = System.currentTimeMillis();logger.info("本次查询:{},花费时间为{}ms",id,endTime-startTime);return user;}
}/**
*通用mapper的使用,可以动态生成实现子类和查询语言适用于单表查询
*/package com.practice.mapper;import com.practice.pojo.User;
import tk.mybatis.mapper.common.Mapper;public interface UserMapper extends Mapper<User> {
}

3创建服务消费者cosumer-demo

  1.pom.xml配置 需要的依赖

 <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 添加OkHttp支持 --><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>3.9.0</version></dependency><!-- Eureka客户端 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency><!--测试--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><!--Hystrix依赖--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency><!--Feign的依赖--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency></dependencies>

  2. application.xml的配置

Spring:application:name: consumer
eureka:client:service-url: #eurekaServer地址defaultZone: http://127.0.0.1:10086/eureka,http://127.0.0.1:10087/eurekaregistry-fetch-interval-seconds: 5 #获取更新服务列表 默认时间为30秒instance:prefer-ip-address: true #当其它服务获取地址时提供ip而不是hostnameip-address: 127.0.0.1 #指定自己的ip信息 不指定的话会自己寻找
ribbon: #修改服务负载均衡的分流规则NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #随机 默认为轮询ConnectTimeout: 250 # ribbon 连接超时时间ReadTimeout: 1000 #Ribbon 数据读取超时时间
feign:hystrix:enabled: true #开启feign的熔断支持默认关闭compression:request:enabled: true # 开启请求压缩mime-types: text/html,application/xml,application/json # 设置压缩的数据类型min-request-size: 2048 # 设置触发压缩的大小下限
logging:level:com.consumer:debug

  3. 创建启动类 和pojo对象类

package com;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;@EnableDiscoveryClient
@SpringBootApplication
//@EnableHystrix
@EnableFeignClients
public class Consumer {
//    @Bean
//    @LoadBalanced //开启负载均衡
//    public RestTemplate restTemplate(){
//    // 使用OKHTTP客户端,只需注入工厂
//       return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
//    }
// 因为Feign 中自动集成 Ribbon 负载均衡 所以不需要自定义RestTemplatepublic static void main(String[] args) {SpringApplication.run(Consumer.class);}
}
/**
*属性类型和user-service中相同但是不用加@table之类的注解
*/
public class User  {private static final long serialVersionUID = 1L;private Long id;// 用户名private String userName;// 密码private String password;// 姓名private String name;// 年龄private Integer age;// 性别,1男性,2女性private Integer sex;// 出生日期private Date birthday;// 创建时间private Date created;// 更新时间private Date updated;//TODO 需要手动添加getter,setter
}

  4. 创建 controller,service,config (dao是测试hystrix时创建的,feign中支持熔断所以不用创建)

package com.consumer.controller;import com.consumer.pojo.User;
import com.consumer.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
@RequestMapping("consume")
public class ConsumerController {@Autowiredprivate UserService userService;@GetMappingpublic List<User> consume(@RequestParam("ids")List<Long> ids){return this.userService.queryUserByIds(ids);}
}package com.consumer.service;import com.consumer.config.UserFeignClient;
import com.consumer.config.impl.UserFeignClientImpl;
import com.consumer.dao.UserDao;
import com.consumer.pojo.User;
//import com.netflix.discovery.DiscoveryClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;import java.util.ArrayList;
import java.util.List;@Service
public class UserService {/*** 根据服务名称,获取服务实例* */@Autowiredprivate UserFeignClient userFeignClient;public List<User> queryUserByIds(List<Long> ids) {List<User> users = new ArrayList<>();ids.forEach(id ->{users.add(userFeignClient.queryById(id));/* try {Thread.sleep(500);
线程睡眠用于测试可以删除} catch (InterruptedException e) {e.printStackTrace();}*/});return users;}}package com.consumer.config;import com.consumer.config.impl.FeignConfig;
import com.consumer.config.impl.UserFeignClientImpl;
import com.consumer.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;@FeignClient(value = "userservice",fallback = UserFeignClientImpl.class,configuration = FeignConfig.class)public interface UserFeignClient {@GetMapping("/user/{id}")public User queryById(@PathVariable("id") Long id);
}package com.consumer.config.impl;import com.consumer.config.UserFeignClient;
import com.consumer.pojo.User;
import org.springframework.stereotype.Component;@Component
public class UserFeignClientImpl implements UserFeignClient {@Overridepublic User queryById(Long id) {User user = new User();user.setId(id);user.setName("请求超时,请稍后重试--feign");return user;}
}package com.consumer.config.impl;import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** 编写配置类定义feign的日志级别 feign支持四种级别* - NONE:不记录任何日志信息,这是默认值。* - BASIC:仅记录请求的方法,URL以及响应状态码和执行时间* - HEADERS:在BASIC的基础上,额外记录了请求和响应的头信息* - FULL:记录所有请求和响应的明细,包括头信息、请求体、元数据*/
@Configuration
public class FeignConfig {@BeanLogger.Level feignLoggerLevel() {return Logger.Level.FULL;}
}

4. 创建zuul网关

1.pom.xml中的依赖

 <dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-zuul</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency></dependencies>

  2. application.yml

server:port: 10010
spring:application:name: gateway
zuul:routes:userservice: userservice/**  #简便方式prefix: /api #添加路由前缀#     path: /userservice/** #这是映射路径
#    serviceId: userservice #指定服务名称
#      url: http://127.0.0.1:8081 映射路径对应的实际url地址
eureka:client:registry-fetch-interval-seconds: 5 #循环获取服务列表service-url:defaultZone: http://127.0.0.1:10086/eurekainstance:prefer-ip-address: trueip-address: 127:0.0.1

  3. 创建启动器

package com.zuul;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy //开启网关功能
public class Zuul {public static void main(String[] args) {SpringApplication.run(Zuul.class);}
}

  测试成功的页面:

转载于:https://www.cnblogs.com/mountainCold/p/10105263.html

认识并学会springCloud的使用相关推荐

  1. 六小时学会SpringCloud

    SpringCloud学习 一 .第一部分 是什么 能干什么 去哪里下 怎么使用了解一个新技术的步骤 版本设置 SpringBoot2.x与SpringCloudH版本 https://start.s ...

  2. 视频教程-Spring Cloud微服务--入门到精通-Java

    Spring Cloud微服务--入门到精通 本系列课程由多位老师共同录制而成,旨在为想要学习Java的用户提供一套系统的成长方案. Java从入门到进阶 ¥59.00 立即订阅 扫码下载「CSDN程 ...

  3. 【微服务】6、一篇文章学会使用 SpringCloud 的网关

    目录 一.网关作用 二.网关的技术实现 三.简单使用 四.predicates (1) 网关路由可配置的内容 (2) 路由断言工厂(Route Predicate Factory) 五.filters ...

  4. 业余草 SpringCloud 教程 | 第一篇: 服务的注册与发现Eureka(Finchley版本)

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/xmt1139057136/article/details/81411887 一.spring clo ...

  5. 史上最简单的 SpringCloud 教程 | 第一篇: 服务的注册与发现(Eureka)

    最新Finchley版本请访问: https://www.fangzhipeng.com/springcloud/2018/08/30/sc-f1-eureka/ 或者 http://blog.csd ...

  6. 【SpringCloud】第五篇: 路由网关(zuul)

    前言: 必需学会SpringBoot基础知识 简介: spring cloud 为开发人员提供了快速构建分布式系统的一些工具,包括配置管理.服务发现.断路器.路由.微代理.事件总线.全局锁.决策竞选. ...

  7. Springcloud整理

    Springcloud 答题技巧: 总:当前问题回答的是那些具体的点 分:以1,2,3,4,5的方式分细节取描述相关的知识点,如果有哪些点不清楚,直接忽略过去 突出一些技术名词(核心概念,接口,类,关 ...

  8. 最简单的 SpringCloud 教程 | 第一篇: 服务的注册与发现Eureka(Finchley版本)

    一.spring cloud简介 鉴于<史上最简单的Spring Cloud教程>很受读者欢迎,再次我特意升级了一下版本,目前支持的版本为Spring Boot版本2.0.3.RELEAS ...

  9. 【SpringCloud】 第十篇: 高可用的服务注册中心

    前言: 必需学会SpringBoot基础知识 简介: spring cloud 为开发人员提供了快速构建分布式系统的一些工具,包括配置管理.服务发现.断路器.路由.微代理.事件总线.全局锁.决策竞选. ...

  10. SpringCloud 教程 | 第一篇: 服务的注册与发现Eureka

    SpringCloud 教程 | 第一篇: 服务的注册与发现Eureka(Finchley版本) 原文首发于:https://www.fangzhipeng.com/springcloud/2018/ ...

最新文章

  1. 两分公支的IPSec***流量走总部测试
  2. angularjs directive 的几点使用技巧
  3. Opencv2.4.9源码分析——HoughLinesP
  4. mac怎么用终端编写c语言视频,【新手提问】有知道用mac终端编c语言的网络编程的人吗?...
  5. SqlServer过滤字段中的中文
  6. 27 PP配置-生产车间控制-工序-定义确认参数
  7. vue限制点击次数_vue点击切换颜色限制个数(用了mui框架)
  8. L2-035 完全二叉树的层序遍历 (25 分)-PAT 团体程序设计天梯赛 GPLT
  9. 数学建模 —— 自回归模型
  10. 【原创】Magisk+Shamiko过APP ROOT检测
  11. 什么是主数据?什么是主数据管理系统?
  12. 重磅|如何利用NBA球员推文预测其球场表现?
  13. Java图书管理系统登陆界面
  14. 微信网页调试8.0.19换掉X5内核,改用xweb,所以x5调试方式已经不能用了,现在有了解决方案
  15. 【Windows Server 2019】路由服务的配置和管理
  16. 【LeetCode击败99%+】猜数字大小
  17. PHP 测试页index.php phpinfo 空白问题
  18. Dota 2 - Character Art Guide
  19. 【历史上的今天】8 月 1 日:中国的第一台计算机成功运行;Microsoft Office 首次推出;今日头条上线
  20. 粗粒度与细粒度的解释

热门文章

  1. 苹果手机显示iphone已停用连接itunes_iTunes备份道理我都懂,但我依然不想备份的?...
  2. c++自动抢购_小黄人汽车手机支架多功能出风口高档可充电全自动导航卡通支架2元优惠券券后价22.9元...
  3. iview admin 使用爬坑
  4. Android转场动画深度解析(3)
  5. Unity调用Android类方法
  6. java基础(十一章)
  7. NBU官方Doc網址https://www.veritas.com/support/en_US/article.DOC5332
  8. Word2013 设置默认缩进
  9. 真题很重要,用科学的态度批判性地对待真题同等重要!
  10. 概率论与数理统计——贝塞尔校正(Bessel‘s Correction)