Springcloud入门学习笔记

1. 项目初始化配置

1. 1. 新建maven工程

使用idea创建maven项目

1. 2. 在parent项目pom中导入以下依赖

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
<properties>
<spring.cloud-version>Hoxton.SR8</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>

2. Eureka使用

2. 1. 创建子module,命名为eureka-server

2. 2. 在eureka-server中添加以下依赖

<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.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

2. 3. 在application.yml中添加以下配置

server:
port: 8900 #应用的端口号
eureka:
client:
service-url:
defaultZone: http://user:123@localhost:8900/eureka #eureka服务的的注册地址
fetch-registry: false #是否去注册中心拉取其他服务地址
register-with-eureka: false #是否注册到eureka
spring:
application:
name: eureka-server #应用名称 还可以用eureka.instance.hostname = eureka-server
security: #配置自定义Auth账号密码
user:
name: user
password: 123

2. 4. 在启动类上架注解

@SpringBootApplication
@EnableEurekaServer

在启动类中加入以下方法,防止spring的Auth拦截eureka请求

@EnableWebSecurity
static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/eureka/**");
super.configure(http);
}
}

2. 5. 创建module名为provider-user为服务提供者

2. 5. 1. 在pom中添加以下依赖
<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-client</artifactId>
</dependency>
2. 5. 2. application.yml配置
server:
port: 7900 #程序启动入口
spring:
application:
name: provider-user #应用名称
eureka:
client:
service-url:
defaultZone: http://user:123@${eureka.instance.hostname}:${server.port}/eureka/
2. 5. 3. 启动类加注解
@SpringBootApplication
@EnableEurekaClient

Controller相关代码如下:

@RestController
public class UserController {
@GetMapping (value = "/user/{id}")
public User getUser(@PathVariable Long id){
User user = new User();
user.setId(id);
user.setDate(new Date());
System.out.println("7900");
return user;
}
@PostMapping (value = "/user")
public User getPostUser(@RequestBody User user){
return user;
}
}

2. 6. 创建module名为consumer-order为服务提供者

2. 6. 1. pom依赖同服务提供者
2. 6. 2. application.yml配置
server:
port: 8010
spring:
application:
name: consumer-order
eureka:
client:
serviceUrl:
defaultZone: http://user:123@${eureka.instance.hostname}:${server.port}/eureka/
2. 6. 3. 启动类
@SpringBootApplication
@EnableEurekaClient
public class ConsumerApp
{
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main( String[] args )
{
SpringApplication.run(ConsumerApp.class,args);
}
}
2. 6. 4. Controller层代码
@RestController
public class OrderController { @Autowired
private RestTemplate restTemplate;
@GetMapping (value = "/order/{id}")
public User getOrder(@PathVariable Long id){
//获取数据
User user = new User();
user.setId(id);
user.setDate(new Date());
user = restTemplate.getForObject("http://provider-user:7900/user/"+id,User.class);
return user;
}
}

2. 7. 启动应用

分别启动Eureka-server、provider-user、consumer-order三个服务

2. 8. 访问地址

http://localhost:8900就可以看到两个服务已经注册到eureka注册中心上了

2. 9. eureka高可用配置

两个节点

#高可用配置,两个节点
spring:
application:
name: eureka-server-ha
profiles:
active: peer1 eureka:
client:
serviceUrl:
defaultZone: https://peer1/eureka/,http://peer2/eureka/
---
server:
port: 8901
spring:
profiles: peer1
eureka:
instance:
hostname: peer1 ---
server:
port: 8902
spring:
profiles: peer2
eureka:
instance:
hostname: peer2

三个节点

#高可用配置,三个
spring:
application:
name: eureka-server-ha
profiles:
active: peer3
eureka:
client:
serviceUrl:
defaultZone: http://peer1:8901/eureka/,http://peer2:8902/eureka/,http://peer3:8903/eureka/
---
spring:
profiles: peer1
eureka:
instance:
hostname: peer1
server:
port: 8901
---
spring:
profiles: peer2
eureka:
instance:
hostname: peer2
server:
port: 8902
---
spring:
profiles: peer3
eureka:
instance:
hostname: peer3
server:
port: 8903

3. Ribbon的使用入门

3. 1. 方式一(默认)

轮询规则

在启动类中restTemplate()方法加入注解@LoadBalanced

RestTemplate 是由 Spring Web 模块提供的工具类,与 SpringCloud 无关,是独立存在的,因 SpringCloud 对 RestTemplate 进行了一定的扩展,所以 RestTemplate 具备了负载均衡的功能

@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}

在启动类上加注解

@RibbonClient(name = "provider-user")

3. 2. 方式二(配置文件自定义)

在application.yml中加入以下配置

#使用配置文件方式实现负载均衡,优先级,配置文件>注解或java代码配置>cloud默认配置
provider-user:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

3. 3. 方式三(Java代码自定义)

自定义一个配置类,返回规则

@RibbonClient(name = "provider-user",configuration = RibbonConfiguration.class)
public class RibbonConfiguration {
@Bean
public IRule getRule(){
return new RandomRule();
}
}

4. Feign学习

什么是feign,是声明式的webservice客户端,解决远程调用,支持JAX-RS,即RestFulWebService

4. 1. 引入依赖

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

4. 2. 使用注解@FeignClient编写feign调用的客户端接口

@FeignClient("provider-user")
public interface UserFeignClient {
@RequestMapping (value = "/user/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable Long id);
@RequestMapping (value = "/user", method = RequestMethod.POST)
public User postUser(@RequestBody User user);
}

4. 3. 在启动类加注解@EnableFeignClients

4. 4. Controller层的调用方法

@Autowired
private UserFeignClient userFeignClient;
@GetMapping (value = "/user/{id}")
public User getUser(@PathVariable Long id){
//获取数据
return this.userFeignClient.getUser(id);
}
@GetMapping (value = "/user")
public User postUser(User user){
return this.userFeignClient.postUser(user);
}

5. hystrix学习

hystrix是Netflix的一个类库,在微服务中,具有多层服务调用,主要实现断路器模式的类库

5. 1. 引入依赖

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

5. 2. 在启动类上加注解

@EnableCircuitBreaker
    1. 在Controller层类的方法上加注解,并编写退回方法,需同名
@HystrixCommand(fallbackMethod = "findByIdFallBack")
public User getOrder(@PathVariable Long id){
//获取数据
User user = new User();
user.setId(id);
user.setDate(new Date());
user = restTemplate.getForObject("http://provider-user/user/"+id,User.class);
System.out.println(Thread.currentThread().getId());
return user;
}
public User findByIdFallBack(Long id){
System.out.println(Thread.currentThread().getId());
User user = new User();
user.setId(1L);
return user;
}

6. springboot的健康监控actuator

actuator主要用于服务健康监控,springboot 1.X和2.x有所不同,本次为2.X

6. 1. 引入依赖包

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

6. 2. 配置

#健康监控配置
management:
endpoint:
health:
show-details: always #是否健康监控显示细节
endpoints:
web:
exposure:
include: hystrix.stream #hystrix保护机制,不直接暴露监控状态
base-path: / #暴露的端点链接

6. 3. 访问

1.X版本

localhost:8080/health

2.X版本

localhost:8080/actuator/health

7. feign配合Hystrix使用

7. 1. 配置文件

feign:
hystrix:
enabled: true # 总开关,可以通过java单独控制client

7. 2. 启动类注解

@EnableFeignClients

7. 3. 控制层

@RestController
public class OrderFeignController {
@Autowired
private UserFeignClient userFeignClient;
@Autowired
private UserFeignNotHystrixClient userFeignNotHystrixClient;
@GetMapping (value = "/order/{id}")
public User getUser(@PathVariable Long id){
//获取数据
return userFeignClient.getUser(id);
} /**
* 测试Feign客户端单独控制
* @param id
* @return
*/
@GetMapping(value = "/user/{id}")
public User getUserNotHystrix(@PathVariable Long id){
//获取数据
return userFeignNotHystrixClient.getUserNotHystrix(id);
}
}

7. 4. 两个FeignClient

一个加了configuration一个没有,加了可以通过注解重写feignBuilder方法单独控制,默认是返回HystrixFeignBuilder

@FeignClient(name = "provider-user", fallback = HystrixClientFallback.class)
public interface UserFeignClient {
@RequestMapping (value = "/user/{id}", method = RequestMethod.GET)
User getUser(@PathVariable Long id);
} @Component
public class HystrixClientFallback implements UserFeignClient{
@Override
public User getUser(Long id) {
System.out.println(Thread.currentThread().getId());
User user = new User();
user.setId(1L);
return user;
}
}
@FeignClient(name = "provider-user1",configuration = ConfigurationNotHystrix.class,fallback = HystrixClientNotHystrixFallback.class)
public interface UserFeignNotHystrixClient {
@RequestMapping (value = "/user/{id}", method = RequestMethod.GET)
User getUserNotHystrix(@PathVariable Long id);
} @Component
public class HystrixClientNotHystrixFallback implements UserFeignNotHystrixClient{
@Override
public User getUserNotHystrix(Long id) {
System.out.println(Thread.currentThread().getId());
User user = new User();
user.setId(1L);
return user;
}
}

7. 5. 配置类

@Configuration
public class ConfigurationNotHystrix { @Bean
@Scope("prototype")
public Feign.Builder feignBuilder(){
return Feign.builder();
}
}

7. 6. 获取异常信息代码

@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello iFailSometimes();
} @Component
static class HystrixClientFallbackFactory implements FallbackFactory<HystrixClient> {
@Override
public HystrixClient create(Throwable cause) {
return new HystrixClient() {
@Override
public Hello iFailSometimes() {
return new Hello("fallback; reason was: " + cause.getMessage());
}
};
}
}

持续更新中

springcloud学习入门的更多相关文章

  1. 【原创】SpringBoot & SpringCloud 快速入门学习笔记(完整示例)

    [原创]SpringBoot & SpringCloud 快速入门学习笔记(完整示例) 1月前在系统的学习SpringBoot和SpringCloud,同时整理了快速入门示例,方便能针对每个知 ...

  2. SpringCloud学习之手把手教你用IDEA搭建入门项目【番外篇】(一)

    之前的文章里,我曾经搭建了一个Springcloud项目,但是那个时候我对于SpringCloud架构的很多组件不甚清楚,只是通过查找资料然后动手稀里糊涂的把一个项目成功搭建起来了,其中有很多不合理和 ...

  3. SpringCloud学习(二):微服务入门实战项目搭建

    一.开始使用Spring Cloud实战微服务 1.SpringCloud是什么? 云计算的解决方案?不是 SpringCloud是一个在SpringBoot的基础上构建的一个快速构建分布式系统的工具 ...

  4. SpringCloud学习笔记(2):使用Ribbon负载均衡

    简介 Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡工具,在注册中心对Ribbon客户端进行注册后,Ribbon可以基于某种负载均衡算法,如轮询(默认 ...

  5. SpringCloud学习笔记(3):使用Feign实现声明式服务调用

    简介 Feign是一个声明式的Web Service客户端,它简化了Web服务客户端的编写操作,相对于Ribbon+RestTemplate的方式,开发者只需通过简单的接口和注解来调用HTTP API ...

  6. SpringCloud学习笔记(4):Hystrix容错机制

    简介 在微服务架构中,微服务之间的依赖关系错综复杂,难免的某些服务会出现故障,导致服务调用方出现远程调度的线程阻塞.在高负载的场景下,如果不做任何处理,可能会引起级联故障,导致服务调用方的资源耗尽甚至 ...

  7. springcloud Config 入门,带视频

    疯狂创客圈 Java 高并发[ 亿级流量聊天室实战]实战系列 [博客园总入口 ] 架构师成长+面试必备之 高并发基础书籍 [Netty Zookeeper Redis 高并发实战 ] 前言 Crazy ...

  8. SpringCloud学习(SPRINGCLOUD微服务实战)一

    SpringCloud学习(SPRINGCLOUD微服务实战) springboot入门 1.配置文件 1.1可以自定义参数并在程序中使用 注解@component @value 例如 若配置文件为a ...

  9. 每天成长一点---WEB前端学习入门笔记

    WEB前端学习入门笔记 从今天开始,本人就要学习WEB前端了. 经过老师的建议,说到他每天都会记录下来新的知识点,每天都是在围绕着这些问题来度过,很有必要每天抽出半个小时来写一个知识总结,及时对一天工 ...

随机推荐

  1. 上海做假证t

    上海做假证[电/薇:187ヘ1184ヘ0909同号]办各类证件-办毕业证-办离婚证,办学位证书,办硕士毕业证,办理文凭学历,办资格证,办房产证不. 这是一个简单的取最大值程序,可以用于处理 i32 数 ...

  2. Unity中利用柏林噪声(perlinnoise)制作摇摆效果

    perlinnoise是unity中Mathf下的一个函数,需要两个float参数x和y进行采样,返回一个0-1的float型. 项目里经常要随机摇摆某些东西,比如摄像机,某个随机运动的目标等等,都可 ...

  3. python小白入门基础(四:浮点型和布尔型)

    # Number (int float bool complex)# (1) float 浮点型 也就是小数# 表达方式一floatvar = 0.98print(floatvar)print(typ ...

  4. I - 乓 (BFS+邻接表)

    USTC campus network is a huge network. There is a bi-directional link between every pair of computer ...

  5. P3311 [SDOI2014]数数 AC自动机+数位DP

    题意 给定一个正整数N和n个模式串,问不大于N的数字中有多少个不包含任意模式串,输出对\(1e^9+7\)取模后的答案. 解题思路 把所有模式串都加入AC自动机,然后跑数位DP就好了.需要注意的是,这 ...

  6. Spring security OAuth2.0认证授权学习第二天(基础概念-授权的数据模型)

    如何进行授权即如何对用户访问资源进行控制,首先需要学习授权相关的数据模型. 授权可简单理解为Who对What(which)进行How操作,包括如下: Who,即主体(Subject),主体一般是指用户 ...

  7. leetcode刷题-58最后一个单词

    题目 给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度.如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词. 如果不存在最后一个单词,请返回 0 . 说明:一 ...

  8. leetcode刷题-47全排列2

    题目 给定一个可包含重复数字的序列,返回所有不重复的全排列. 思路 其思路与46题完全一致,但是需要与组合总和2题一般,在同一层取出重复元素.因此可以在每一层设置一个set()类型,将访问过的元素放入 ...

  9. Dos拒绝服务Syn-Flood泛洪攻击--Smurf 攻击(一)

    Dos拒绝服务利用程序漏洞或一对一资源耗尽的Denial of Service 拒绝服务DDos 分布式拒绝服务 多对一 Syn-Flood泛洪攻击 发送syn包欺骗服务器建立半连接 攻击代码,利用s ...

  10. JVM直接内存(Direct Memory)

    直接内存 1.直接内存不是虚拟机运行时数据区的一部分,也不是<Java虚拟机规范>中定义的内存区域. 2.直接内存是Java堆外的.直接向系统申请的内存区间. 3.简单理解: java p ...