【Java学习日记】SpringCloud-Eureka搭建分布式架构

8 篇文章 0 订阅
1 篇文章 0 订阅

SpringCloud

创建父工程

SpringBoot/Maven工程

https://start.spring.io

https://start.aliyun.com

修改pom文件,将packging设置为

<packaging>pom</packaging>

1. 创建Eureka服务工程(注册中心)

创建一个SpringBoot工程

导包

相关pom文件依赖配置
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

<!--添加springmvc-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>
在SpringBoot配置文件中配置Eureka服务(这里用的是application.properties文件)
#设置服务器端口
server.port=9000
#设置应用程序名称     名字不许用下划线,不支持服务调用
spring.application.name=sc-demo-server
#主机地址
eureka.instance.hostname=localhost
#表示不向注册中心注册(因为自己就是服务器)
eureka.client.register-with-eureka=false
#表示不向注册中心调用服务
eureka.client.fetch-registry=false
#服务的地址
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka
在启动类中添加Eureka注解开启Eureka服务
@SpringBootApplication
@EnableEurekaServer//启动Eureka
public class ScDemoServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScDemoServerApplication.class, args);
    }

}
运行启动类

https://localhost:9000/

运行结果

2. 创建Eureka服务提供者工程

创建一个SpringBoot工程

导包

相关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>
在SpringBoot配置文件中配置Eureka发布服务配置
#服务器端口
server.port=9001
#配置发布服务地址
spring.application.name=sc-demo-provider
eureka.client.service-url.defaultZone=http://localhost:9000/eureka
在启动类中开启Eureka
@SpringBootApplication
@EnableEurekaClient
public class ScDemoProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScDemoProviderApplication.class, args);
    }

}
编写控制器提供服务(使用的是http协议

先创建一个学生实体类

public class Student {
    private Integer xh;
    private String name;
    private String sex;
    private Integer age;

    //省略构造方法和setter和getter类
}

编写一个构造器

@RestController
public class TestController {
    //接收请求(服务) 返回json
    @RequestMapping("/getData")
    public Student getData(){
        //返回一个学生
        return new Student(101, "张三", "人妖", 21);
    }
}

运行启动类,运行结果

3. 创建web(消费者)工程显示学生信息

创建一个SpringBoot工程

导包

相关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>
在SpringBoot文件中添加Eureka发布服务配置
#服务器
server.port=9002
#服务的名称
spring.application.name=eureka-consumer
#指定注册中心:eureka服务器
eureka.client.service-url.defaultZone=http://localhost:9000/eureka
在启动类中开启Eureka
@SpringBootApplication
@EnableEurekaClient
public class ScDemoConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScDemoConsumerApplication.class, args);
    }
    
    //在启动类中创建RestTemplate对象用于调用http服务
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}
开发控制器调用业务
  1. 将提供者中的实体类复制到消费者工程
  2. 开发控制器
@RestController
public class StudentController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/showStu")
    public Student showStu(){
        //1.restTemplate调用http协议的请求
        //1.1使用RestTemplat对象调用http服务(不建议直接调http服务)没有经过注册中心
        //支持将json转化为java对象
        //Student stu = restTemplate.getForObject("http://localhost:9001/getData",Student.class);

        //1.2.使用restTemplat对象调用注册中心http服务(基于服务名称调用):
        //注册中心的服务名称:SC-PROVIDER
        Student stu = restTemplate.getForObject("http://SC-DEMO-PROVIDER/getData", Student.class);
        return stu;
    }
}

运行启动类

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WNpPeEbf-1689179382428)(C:\Users\89443\AppData\Roaming\Typora\typora-user-images\image-20230711161537852.png)]

这时候发现页面找不到,原因是使用restTemplat对象调用注册中心http服务,不支持通过"http://SC-DEMO-PROVIDER"类似的服务名称方式去寻找服务,此时需要在启动类中添加一个注解配置"@LoadBalanced"

@SpringBootApplication
@EnableEurekaClient
public class ScDemoConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScDemoConsumerApplication.class, args);
    }
    
    //在启动类中创建RestTemplate对象用于调用http服务
    @Bean
    @LoadBalanced //支持使用服务名称发现服务进行调用,且支持负载均衡
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

重启消费者的启动类,成功!

springcloud五大组件:

1、Eureka,实现服务治理;

2、Ribbon,主要提供客户侧的软件负载均衡算法;

3、Hystrix,断路器,保护系统,控制故障范围;

4、Zuul是路由,负载均衡等多种作用;—>GateWay网关

5、Config是配置管理作用。

6、feign 组件实现服务调用

SpringCloud其他组件

1、Ribbon负载及服务集群

Ribbon淘汰便不多赘述,只是有这个东西最好不能忘了

2、feign组件调用Eureka服务

消费者工程的pom中导入openfeign依赖

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

在启动类上开启fegin调用

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients    //启动feign
public class ScDemoConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScDemoConsumerApplication.class, args);
    }

    //在启动类中创建RestTemplate对象用于调用http服务
    @Bean
    @LoadBalanced //支持使用服务名称发现服务进行调用,且支持负载均衡
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

创建第二个提供者工程

基本类似,provider端口配置为9001,provider2端口配置要改为9003,避免冲突

@RestController
public class TestController {
    //provider的测试类
    @RequestMapping("/getStudentData")
    public Student getStudentData(){
        System.out.println("服务器A......port:9001");
        return new Student(101,"陈猛哥","男",21);
    }
}
@RestController
public class TestController {
    //provider2的测试类
    @RequestMapping("/getStudentData")
    public Student getStudentData(){
        System.out.println("服务器B......port:9003");
        return new Student(101,"陈猛哥","男",21);
    }

}

运行就可以看到两个服务器交替执行,具体图就不贴了,节约时间

3、断路器Hystrix

断路器概念:

由于网络原因或者自身的原因,服务并不能保证100%可用,如果单个服务出现问题,调用这个服务就会出现线程阻塞,此时若有大量的请求涌入,Servlet容器的线程资源会被消耗完毕,导致服务瘫痪。服务与服务之间的依赖性,故障会传播,会对整个微服务系统造成灾难性的严重后果,这就是服务故障的“雪崩”效应(使用熔断防止雪崩效应的产生,支持容错处理)

断路器实现:

在消费者的pom文件中添加依赖

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

实际操作中可以不写version,会自动寻找合适的版本导入

消费者的启动类中添加注释

@EnableHystrix  //开启熔断支持

方法一:给测试接口添加熔断支持

@RequestMapping("/showStudent")
//当前服务调用出错啦,调用默认方法
@HystrixCommand(fallbackMethod = "error")
public Student showStudent(){
    //调用eureka服务获取学生信息
    //1.使用RestTemplate对象调用http服务
    // 1.1使用RestTemplate对象调用http服务(没有基于注册中心:没有找服务调用)
    //注意:支持将json转化为java对象:{"xh":101,"name":"陈猛哥","sex":"男","age":21}
    //Student stu=restTemplate.getForObject("http://localhost:9001/getStudentData",Student.class);

    //1.2 用RestTemplate对象调用http服务(基于eureka服务调用)
    //Student stu=restTemplate.getForObject("http://服务名称/请求路径",Student.class);
    Student stu=restTemplate.getForObject("http://EUREKA-PROVIDER/getStudentData",Student.class);
    return stu;
}

//当发生服务调用错语时,调用error
public Student error(){
        return new Student(110,"靖哥哥","男",21);
}

方法二:就是给fegin添加熔断支持

在springboot配置文件中开启fegin熔断支持

feign.hystrix.enabled=true

在Service接口上添加注释

//关联服务
@FeignClient(value = SC-DEMO-PROVIDER",fallbackFactory =HystrixFallbackFactory.class )

HystrixFallbackFactory是自定义的类

service包下添加HystrixFallbackFactory.java

@Component
public class HystrixFallbackFactory implements FallbackFactory<StudentService> {
    @Override
    public StudentService create(Throwable throwable) {
        /*return new StudentService() {
            @Override
            public Student getStudentInfo() {
                //日志记录
                return new Student(201,"小姐姐","女",58);
            }
        };*/
        //使用lambda
        return ()->new Student(201,"小姐姐","女",58);
    }
}

当然,这样编写类还是过于复杂,推荐使用以下类:

@Component
public class HystrixFallbackFactory implements StudentService {
    @Override
    public Student getStudent() {
        return new Student(109,"通不了","",0);
    }
}

下一篇文章会讲如何使用SpringBoot+SpringCloud+MyBatis+MySql搭建学生管理系统

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值