栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringCloud微服务注册和调用小案例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringCloud微服务注册和调用小案例

1 Spring Cloud简介

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

Netflix

  • Eureka:注册中心
  • Zuul:服务网关
  • Ribbon:负载均衡
  • Feign:服务调用
  • Hystrix:熔断器

以上只是其中一部分,架构图:

2 微服务场景模拟 2.1 创建父工程

先创建一个父工程,后续的工程都以这个工程为父,使用
Maven的聚合和继承。统一管理子工程的版本和配置
pom.xml文件:



    4.0.0

    org.example
    springcloudwork
    pom
    1.0-SNAPSHOT
    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.5.RELEASE
        
    

    
        1.8
        Greenwich.SR1
        2.1.5
        5.1.46
    

    
        
            
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
            
            
                tk.mybatis
                mapper-spring-boot-starter
                ${mapper.starter.version}
            
            
            
                mysql
                mysql-connector-java
                ${mysql.version}
            
        
    
    
        
            org.projectlombok
            lombok
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


2.2 创建服务提供者 2.2.1 创建Module

选中父工程,创建子工程:
pom.xml文件:



    
        springcloudwork
        org.example
        1.0-SNAPSHOT
    
    4.0.0

    user-service

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            tk.mybatis
            mapper-spring-boot-starter

        
        
        
            mysql
            mysql-connector-java
        
    



2.2.2 编写配置文件

创建启动类和 user-servicesrcmainresourcesapplication.yml 属性文件,这里我们采用了yal语法,而不是properties

server:
  port: 9091
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springcloud
    username: root
    password: 147258
mybatis:
  type-aliases-package: com.example.user.pojo

使用Mysql图形界面工具,导入springclound.sql脚本
链接:https://pan.baidu.com/s/1KHaLOU3Hp4yvGm8ij-VzWg
提取码:dsbr

2.2.3 编写代码

启动类

@SpringBootApplication
@MapperScan("com.example.user.mapper")
public class UserApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }
}

实体类

@Data
@Table(name = "tb_user")
public class User {
    // id
    @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;
}

UserMapper

public interface UserMapper extends Mapper {
}

Service

@Service
public class UserService {
    @Autowired(required = false)
    private UserMapper userMapper;

    public User queryById(Long id){
        return userMapper.selectByPrimaryKey(id);
    }
}

controller
对外提供REST风格web 服务,根据id查询用户

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User queryById(@PathVariable Long id){
        return userService.queryById(id);
    }

}

2.2.4 启动并测试

启动项目,访问http://localhost:9091/user/7

2.3 创建服务调用者 2.3.1 创建Module

与上面类似,这里不再赘述,需要注意的是,我们调用 user-service 的功能,因此不需要Mybatis相关依赖了拷贝之前的user-service 模块,更改响应的坐标
pom.xml



    
        springcloudwork
        org.example
        1.0-SNAPSHOT
    
    4.0.0

    consumer-demo

    
        
            org.springframework.boot
            spring-boot-starter-web
        
    

2.3.2 编写代码

启动类

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

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

Spring提供了一个RestTemplate模板工具类,对基于HTTP的客户端进行了封装,并且实现了对象与json的序列化和反序列化,非常方便。RestTemplate并没有限定HTTP的客户端类型,而是进行了抽象,目前常用的3种都有支持:

  • HTTPClient
  • OkHTTP
  • JDK原生的URLConnection(默认的)

实体类

@Data
public class User {
    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;
}

controller

@RestController
@RequestMapping("/consumer")
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/{id}")
    public User queryById(@PathVariable Long id){
        String url = "HTTP://localhost:9091/user/" + id;
        return restTemplate.getForObject(url, User.class);
    }
    
}
2.3.3 启动测试

因为我们没有配置端口,那么默认就是8080,我们访问:http://localhost:8080/consumer/7

2.4 创建Eureka注册中心
  • Eureka就好比是滴滴,负责管理、记录服务提供者的信息。服务调用者无需自己寻找服务,而是把自己的需求告诉Eureka,然后Eureka会把符合你需求的服务告诉你。
  • 同时,服务提供方与Eureka之间通过“心跳” 机制进行监控,当某个服务提供方出现问题,Eureka自然会把它从服务列表中剔除。
  • 这就实现了服务的自动注册、发现、状态监控。
2.4.1 创建Module

pom.xml



    
        springcloudwork
        org.example
        1.0-SNAPSHOT
    
    4.0.0

    eureka-server

    
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-server
        
    


2.4.2 编写代码

启动类

@EnableEurekaServer  //声明当前应用时Eureka服务
@SpringBootApplication
public class EurekaApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaApplication.class, args);
    }
}

yml配置文件

server:
  port: 10086
spring:
  application:
    name: eureka-server
eureka:
  client:
    #eureka的服务地址,如果是集群,需要指定其他集群eureka地址
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
    # 不注册自己
    register-with-eureka: false
    # 不抓取服务
    fetch-registry: false
  server:
    enable-self-preservation: false # 关闭自我保护模式(缺省为打开)
    eviction-interval-timer-in-ms: 10000 # 扫描失效服务的间隔时间(缺省为60*1000ms)
2.4.3 测试

启动服务,并访问:http://127.0.0.1:10086/

目前只有127.0.0.1 一个Eureka集群,还没有注册任何服务

2.5 Eureka客户端和服务端注册 2.5.1 注册服务提供者
  1. 给user-service添加依赖
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
  1. 在启动类上开启Eureka客户端功能
@EnableDiscoveryClient //开启Eureka客户端发现功能
@SpringBootApplication
@MapperScan("com.example.user.mapper")
public class UserApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }
}
  1. 编写配置
server:
  port: 9091
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springcloud
    username: root
    password: 147258
  application:
    name: user-service
mybatis:
  type-aliases-package: com.example.user.pojo
eureka:
  client:
    service-url:
      defaultZone: HTTP://127.0.0.1:10086/eureka

这里我们添加了spring.application.name属性来指定应用名称,将来会作为应用的id使用
4. 重启项目
重启项目,访问Eureka监控页面查看

user-service注册成功

2.5.2 注册服务消费者
  1. 给consumer-demo添加依赖
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
  1. 在启动类上开启Eureka客户端功能
@EnableDiscoveryClient //开启Eureka客户端
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
  1. 编写配置
spring:
  application:
    name: consumer-demo
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka

这里我们添加了spring.application.name属性来指定应用名称,将来会作为应用的id使用

  1. 重启项目
    重启项目,访问Eureka监控页面查看
2.6 使用Feign配置负载均衡和Hystrix支持

负载均衡

  • 在刚才的案例中,我们启动了一个user-service,然后通过DiscoveryClient来获取服务实例信息,然后获取ip和端口来访问。 但是实际环境中,我们往往会开启很多个user-service的集群。此时我们获取的服务列表中就会有多个,到底该访 问哪一个呢?
  • 一般这种情况下我们就需要编写负载均衡算法,在多个实例列表中进行选择。

Hystrix

  • Hystrix是Netflix开源的一个延迟和容错库,用于隔离访问远程服务,防止出现级联失败。
  • 服务器支持的线程和并发数有限,请求一直阻塞,会导致服务器资源耗尽,从而导致所有其它服务都不可用,形成雪崩效应。
  • Hystrix解决雪崩问题的手段,主要包括:
    • 线程隔离
    • 服务降级
2.6.1 开启Feign功能
  1. 导入依赖
    consumer-demo的pom文件
		
            org.springframework.cloud
            spring-cloud-starter-openfeign
        
  1. Feign的客户端
    创建Feign的动态代理接口
@FeignClient("user-service")
public interface UserClient {
    //目的是要生成一个访问地址
    //http://user-service/user/123
    @GetMapping("/user/{id}")
    public User queryById(@PathVariable("id") Long id);
}
  • 首先这是一个接口,Feign会通过动态代理,帮我们生成实现类。这点跟Mybatis的mapper很像
  • @FeignClient,声明这是一个Feign客户端,同时通过 value 属性指定服务名称
  • 接口中的定义方法,完全采用SpringMVC的注解,Feign会根据注解帮我们生成URL,并访问获取结果
  • @GetMapping中的/user,请不要忘记;因为Feign需要拼接可访问的地址

创建基于Feign的controller方法

@RestController
@RequestMapping("/feign")
public class ConsumerFeignController {

   @Autowired(required = false)
   private UserClient userClient;

   //通过调用UserClient接口生成的代理对象来完成操作
   @GetMapping("{id}")
   public User queryById(@PathVariable Long id){
       return userClient.queryById(id);
   }
}

  1. 开启Feign功能
    在 ConsumerApplication 启动类上,添加注解,开启Feign功能
@EnableFeignClients //开启Feign功能
@EnableDiscoveryClient //开启Eureka客户端
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
  1. 启动测试
    访问接口:http://localhost:8080/feign/2
2.6.2 配置负载均衡

Feign中本身已经集成了Ribbon依赖和自动配置,因此不需要额外引入依赖,也不需要再注册 RestTemplate 对象。
因为ribbon内部有重试机制,一旦超时,会自动重新发起请求。如果不希望重试,可以添加配置:
修改 consumer-demosrcmainresourcesapplication.yml 添加如下配置 :

ribbon:
  ConnectTimeout: 1000 # 连接超时时长
  ReadTimeout: 2000 # 数据通信超时时长
  MaxAutoRetries: 0 # 当前服务器的重试次数
  MaxAutoRetriesNextServer: 0 # 重试多少次服务
  OkToRetryOnAllOperations: false # 是否对所有的请求方式都重试
2.6.3 配置Hystrix支持

Feign默认也有对Hystrix的集成:
只不过,默认情况下是关闭的。需要通过下面的参数来开启:

  1. 修改 consumer-demosrcmainresourcesapplication.yml 添加如下配置:
feign:
  hystrix:
    enabled: true # 开启Feign的熔断功能
  1. 定义一个类,实现刚才编写的UserClient接口,作为fallback的处理类
@Component
public class UserClientFallback implements UserClient {

   @Override
   public User queryById(Long id) {
       User user = new User();
       user.setId(id); //在实体类中补充get set方法
       user.setName("用户异常");
       return user;    }
}
  1. 在UserClient接口中,指定刚才编写的实现类
@FeignClient(value = "user-service",fallback = UserClientFallback.class)
public interface UserClient {
    //目的是要生成一个访问地址
    //http://user-service/user/123
    @GetMapping("/user/{id}")
    public User queryById(@PathVariable("id") Long id);
}
  1. 重启测试
    重启启动 consumer-demo 并关闭 user-service 服务,然后在页面访问:http://localhost:8080/feign/7

    实现了在访问不到资源的时候返回友好提示
    ,而不是拥堵网络
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/685954.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号