1.SpringCloud入门
Spring cloud是一个基于Spring Boot实现的服务治理工具包,用于微服务架构中管理和协调服务的。
Spring Cloud是一系列框架的有序集合。
服务发现——Netflix Eureka
客服端负载均衡——Netflix Ribbon\Feign
断路器——Netflix Hystrix
服务网关——Netflix Zuul
分布式配置——Spring Cloud Config
1.1 搭建注册中心
1.创建多模块工程
springcloud-parent
springcloud-eureka-server //注册中心EurekaServer
springcloud-order-server //订单服务EurekaClient ,消费者
springcloud-user-server //用户服务EurekaClient ,提供者
2.springcloud-parent管理依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<groupId>cn.itsource.springcloud</groupId>
<artifactId>springcloud-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<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>Finchley.SR1</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
3.springcloud-eureka-server导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
4.主配置类
/**
* @EnableEurekaServer :开启注册中心
*/
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication1000 {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication1000.class);
}
}
5.配置文件application.yml
server:
port: 1000
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false #禁用注册中心向自己注册
fetchRegistry: false #不让注册中心获取服务的注册列表
serviceUrl:
defaultZone: http://localhost:1000/eureka/
#注册中心的注册地址 ,其他微服务需要向这个地址注册
1.2 搭建提供者服务
修改 springcloud-user-server
1.导入依赖
<dependencies>
<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-web</artifactId>
</dependency>
</dependencies>
2.创建配置类
//@EnableDiscoveryClient:开启注册中心客户端 EurekaClient
@SpringBootApplication
@EnableDiscoveryClient
public class UserServerApplication {
public static void main(String[] args) {
SpringApplication.run(UserServerApplication2000.class);
}
}
3.配置文件
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1000/eureka/ #注册中心地址
server:
port: 2000
spring:
application:
name: user-server
1.3 搭建消费者服务
修改 springcloud-order-server ,步骤同上(搭建提供者服务)
1.4 使用ip注册
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1000/eureka/ #注册中心地址
instance:
prefer-ip-address: true #使用ip地址注册
instance-id: order-server #指定服务的id
2.服务完成通信
1.编写aomain : user
public class User {
private Long id;
private String name;
private String password;
public User() {
}
public User(Long id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public Long getId() {
return id;
}
2.编写 AjaxResult
public class AjaxResult {
private Boolean success = true;
private String message;
private User data;
2.1 user-server提供者服务编写接口
1.依赖公共模块
<dependency>
<groupId>cn.itsource.springcloud</groupId>
<artifactId>springcloud-common-user</artifactId>
<version>...</version>
</dependency>
2.创建controller
//用户提供者服务
@RestController
public class UserProviderController {
@GetMapping("/user/{id}")
public User getUserById(@PathVariable("id")Long id){
return new User(id,"张三" , "123");
}
}
2.2 order-server消费者服务
1.依赖公共模块
<dependency>
<groupId>cn.itsource.springcloud</groupId>
<artifactId>springcloud-common-user</artifactId>
<version>...</version>
</dependency>
2.定义RestTemplate的bean
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
3.定义消费者的Controller
@RestController
public class OrderConsumerController {
@Autowired
private RestTemplate restTemplate ;
@GetMapping("/order/user/{id}")
public User getUserById(@PathVariable("id") Long id){
//拼接url路径
String url = "http://localhost:2000/user/"+id;
User user = restTemplate.getForObject(url, User.class);
return user;
}
}
3.EurekaServer高可用集群
3.1 单节点故障
如果只有一个EurekaSever,如果EurekaSever挂了那么整个微服务都不可用 EurekaServer高可用集群
3.2 搭建EurekaServer集群
1.创建两个本地域名 C:\Windows\System32\drivers\etc\hosts
127.0.0.1 peer1
127.0.0.1 peer2
2.修改注册中心springcould-eureka-server
spring:
profiles:
active: peer1
---
server:
port: 1000
eureka:
instance:
hostname: peer1 #主机
client:
registerWithEureka: false #禁止注册中心向自己注册
fetchRegistry: false #禁止注册中心拉取注册地址清单
serviceUrl: #微服务向注册中心注册的地址
defaultZone: http://peer2:1001/eureka/
spring:
profiles: peer1
---
server:
port: 1001
eureka:
instance:
hostname: peer2 #主机
client:
registerWithEureka: false #禁止注册中心向自己注册
fetchRegistry: false #禁止注册中心拉取注册地址清单
serviceUrl: #微服务向注册中心注册的地址
defaultZone: http://peer1:1000/eureka/
spring:
profiles: peer2
注意:这里使用的SpringBoot多环境配置的方式 来实现多个Eureka的配置,启动的时候需要修改 spring.profiles.active=peer1来指定启动使用哪个配置 , 然后IDEA的启动器需要取消勾选:
3.修改EurekaClient
eureka:
client:
serviceUrl:
defaultZone: http://peer1:1000/eureka/,http://peer2:1001/eureka/ #注册中心地址
4 Ribbon
ribbon是负载均衡器,是基于RestTemplate ,它赋予了RestTemplate 负载均衡的能力
提供者user-server集群,修改配置
eureka:
client:
serviceUrl:
defaultZone: http://peer1:1000/eureka/,http://peer2:1001/eureka/ #注册中心地址
instance:
prefer-ip-address: true #使用ip地址注册
instance-id: user-server1 #指定服务的id
server:
port: 2000
spring:
application:
name: user-server
注意:instance-id需要修改 , 而 spring.application.name 不需要修改 , 端口需要修改
4.1 order-server集成Ribbon
1.导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
2…修改RestTemplate的Bean的定义
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
@LoadBalanced :ribbon的负载均衡标签,赋予RestTemplate有负债均衡的能力
3.修改Controller调用方式
@GetMapping("/order/user/{id}")
public User getUserById(@PathVariable("id") Long id){
System.out.println("OrderConsumerController.getUserById被调用了......");
String url = "http://user-server/user/"+id;
User user = restTemplate.getForObject(url, User.class);
return user;
}
ribbon默认使用的轮询策略
5.Feign
基于Ribbon封装的客户端负载均衡器
5.1 Feign的集成
1.导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.配置类开启Feign
@EnableFeignClients
3.编写Feign的接口
@FeignClient(value="user-server")
public interface UserFeignClient {
@GetMapping("/user/{id}")
User getUserById(@PathVariable("id")Long id);
}
4.调用
@RestController
public class DeptConsumerController {
@Autowired
private UserFeignClient userFeignClient ;
@GetMapping("/dept/user/{id}")
public User getUserById(@PathVariable("id") Long id){
User user = userFeignClient.getUserById(id); //使用Feign的接口调用
return user;
}
}
6.Hystrix
解决服务器故障(雪崩)的一个组件 ,它可以实现:隔离 ,熔断 ,降级,缓存
-
隔离 :包括线程池隔离和信号量隔离,限制调用分布式服务的资源使用,某一个调用的服务出现问题不会影响其他服务调用。
-
熔断 :当请求次数达到规定的阀值都出现服务故障(超时),Hystrix就把服务标记为短路状态.
-
降级 :高并发情况下 ,为了保证一些主要的服务有足够的资源不出问题 ,会认为的关掉一些无关紧要的服务,然后返回一些托底的数据,给用户一个友好的提示。
-
缓存 :Hystrix内部会把请求做缓存
6.1 Ribbon集成Hystrix
1.导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2.controller方法贴注解
@RestController
@RequestMapping("/order")
public class OrederController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/user/{id}")
@HystrixCommand(fallbackMethod = "getUserByIdFallback")
public AjaxResult getUserById(@PathVariable("id")Long id){
String url = "http://localhost:3000/user/"+id;
User user = restTemplate.getForObject(url, User.class);
AjaxResult ajaxResult = new AjaxResult();
ajaxResult.setData(user);
return ajaxResult;
}
//托底方法
public AjaxResult getUserByIdFallback(@PathVariable("id")Long id){
AjaxResult ajaxResult = new AjaxResult();
ajaxResult.setSuccess(false);
ajaxResult.setMessage("抱歉,服务器很忙,稍后再来哦");
return ajaxResult;
}
}
6.2 Feign集成Hystrix
1.开启Hystrix
application.yml
feign:
hystrix:
enabled: true #开启熔断支持
2.controller调用
@RestController
@RequestMapping("/order")
public class OrederController {
@Autowired
private UserFrignClient userFrignClient;
@GetMapping("/user/{id}")
public User getUserById(@PathVariable("id")Long id){
User user = userFrignClient.getUserById(id);
return user;
}
}
3.修改Fiegn客户端接口
@FeignClient(value = "user-server",fallback = UserFeignClientFallback.class)
public interface UserFrignClient {
@GetMapping("/user/{id}")
User getUserById(@PathVariable("id")Long id);
}
4.托底实现
@Component
public class UserFeignClientFallback implements UserFrignClient {
@Override
public User getUserById(Long id) {
System.out.println("这是托底数据方法哦。。。。。");
return new User(-1L,"拖低数据","null");
}
}
7.SpirngCloud ZUUL
Zuul是一个SpringCloud的网关组件 , 它是微服务的入口,网络关卡 ,通过Zuul我们可以实现请求的分发(负载均衡),鉴权,限流等等操作。
7.1 zuul的基本使用
1.导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
2.配置开开启Zuul
@SpringBootApplication
//开启代理网管
@EnableZuulProxy
public class SpringCould_Zuul_Server {
public static void main(String[] args) {
SpringApplication.run(SpringCould_Zuul_Server.class, args);
}
}
3.配置文件配置zuul
zuul:
ignored-services: "*"
prefix: "/servers"
routes:
order-server: "/order/**"
order-server1: "/order1/**"
user-server: "/user/**"
4四.自定义Filter实现登录检查
@Component
public class LoginCheckFilter extends ZuulFilter {
public static final int LOGIN_CHECK_FILTER_ORDER = 1;
@Override
public String filterType() {
return PRE_TYPE;
}
@Override
public int filterOrder() {
return LOGIN_CHECK_FILTER_ORDER;
}
//返回true执行run方法 ,否则不执行
@Override
public boolean shouldFilter() {
//login路径放行,其他全部拦截
//获得请求对象
RequestContext context = RequestContext.getCurrentContext();
//获取对象路径
HttpServletRequest request = context.getRequest();
String url = request.getRequestURI();
//判断路径是否为login
if(url.toUpperCase().contains("login")){
return false;
}
return true;
}
@Override
public Object run() throws ZuulException {
//获取请求对象
RequestContext currentContext = RequestContext.getCurrentContext();
HttpServletRequest request = currentContext.getRequest();
//获取响应对象
HttpServletResponse response = currentContext.getResponse();
//设置响应编码
response.setContentType("application/json;charset=utf-8");
//根据请求对象获取响应头
String token = request.getHeader("x-token");
//判断是否有x-token,没有给出提示
if (StringUtils.isBlank(token)){
try {
HashMap<String, String> map = new HashMap<>();
map.put("success", "false");
map.put("message", "请你先登录");
response.getWriter().print(JSON.toJSONString(map));
} catch (IOException e) {
e.printStackTrace();
}
//阻止放行
currentContext.setSendZuulResponse(false);
}
return null;
}
}
8.配置中心config
集中管理微服务的配置: SpringCloud-config 是分布式配置中心组件
8.1 集成配置中心
1.使用码云创建远程仓库
https://blog.csdn.net/weixin_41950971/article/details/83894949
2.导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
3.配置类开启配置中心
@EnableConfigServer:开启配置中心
4.配置文件
eureka:
instance:
prefer-ip-address: true
instance-id: config-server:5000
client:
serviceUrl:
defaultZone: http://peer1:1000/eureka/,http://peer2:1001/eureka/
server:
port: 5000
spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: 码云地址
username: 码云账号
password: 码云密码
5.测试
http://localhost:6001/application-dept-test.yml
8.2 修改springcould-zuul-server微服务
1.导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
2.创建bootstrap.yml配置文件 - 删除原来的
spring:
cloud:
config:
uri: http://localhost:5000
name: application-zuul
profile: dev
3.测试
http://localhost:6001/application-zuul-test.yml
369

被折叠的 条评论
为什么被折叠?



