简单Spring Cloud 微服务框架搭建

微服务是现在比较流行的技术,对于程序猿而言,了解并搭建一个基本的微服务框架是很有必要滴。

微服务包含的内容非常多,一般小伙伴们可以根据自己的需求不断添加各种组件、框架。

一般情况下,基本的微服务框架包含:框架:注册中心、负载均衡、声明式服务(feign)、容错(hystrix)、网关(权限)gateway 和 配置(resource)

注册中心:现在比较常用的有eureka、nacos

负载均衡:包括feign、ribbon等技术,相关对比可以参考另一位老哥的博客:《负载均衡之feign与ribbon对比》

服务间调用:包括resttemplate、feign等等

熔断:hystrix

网关:gateway,(zuul已经逐渐被弃用)

配置中心:config server 、 config clent

本章主要采用 eureka+feign+hystrix+gateway+config 的组合搭建一个基础框架,环境采用idea。

注册中心 

首先新建一个spring工程,spring-boot版本可以选择, 2.1.9.RELEASE。

在新建的project上右键,新建module,选择Spring Initializr

下一步,设置对应的包名,artifact名称,这些可以根据自己的项目需要自己命名。

next,

 然后下一步,完成即可。这种方式是直接将Spring管网上对应的module下载到你的项目中,非常方便。

然后再application.yml文件中设置你对应的注册中心的端口,访问方式等信息。

server:
  port: 8761

eureka:
  instance:

    hostname: localhost
  client:
    #自己是注册中心,不需要注册自己
    registerWithEureka: false
    #自己是注册中心不需要发现服务
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

在启动类中加入对应注解:

@SpringBootApplication
//声明自己是注册中心
@EnableEurekaServer
public class HsddEurekaApplication {

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

}

  

 业务逻辑服务 

业务逻辑服务可以按功能或逻辑进行分类,分成多个微服务来提供,保证整体的可用性。

在project中新建一个目录,比如,service目录。将业务逻辑相关的微服务都放到这里面。

新建spring boot modul,同上面一样,不过可以不选spring cloud配置项。

 然后再main.java下面创建对应的各层目录,这里没啥好说的。

在application启动类中,我们需要添加对应注解,

package com.fencer.userdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient  #注册到注册中心
@EnableFeignClients  #服务间负载均衡与声名式服务
public class UserDemoApplication {

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

} 

在业务逻辑微服务中,需要置application.yml,需要将你的服务注册到注册中心,才能被发现调用

#服务端口
server:
  port: 8762

spring:
  application:
    name: user-demo   #注册的服务名称
  profiles:
    active: dev
  devtools:
    restart:
      enabled: true
      trigger-file: devtools.tg

#注册中心地址
eureka:
  instance:
    prefer-ip-address: true
    instance-id: 127.0.0.1:${server.port}
    hostname: localhost
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
    register-with-eureka: true
    fetch-registry: true

  

 服务间声明式调用及熔断

服务间声明式调用及熔断比较简单,

新建一个业务逻辑服务,在启动类中加入feign、hystrix相关注解

package com.fencer.orderdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients  
@EnableHystrix  //熔断
public class OrderDemoApplication {

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

}

  创建一个调用对象的接口,接口与服务提供方,方法名、参数完全一致

package com.fencer.orderdemo.service;

import com.fencer.orderdemo.fallback.MyFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author : 
 * @version V1.0
 * @Project: hsdd
 * @Package com.fencer.orderdemo.service
 * @Description: TODO
 * @date Date : 2019年10月23日 19:49
 */
@FeignClient(value = "user-demo", fallback = MyFallback.class)
public interface UserDemoFeignService {

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    String getUser(@PathVariable("id") int id);

    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    String home(@RequestParam String name);
}

  添加统一降级处理方法,在服务提供方没有响应时进行处理。

package com.fencer.orderdemo.fallback;

import com.fencer.orderdemo.service.UserDemoFeignService;
import org.springframework.stereotype.Component;

/**
 * @author : 
 * @version V1.0
 * @Project: hsdd
 * @Package
 * @Description: TODO
 * @date Date : 2019年10月24日 10:46
 */
@Component
public class MyFallback implements UserDemoFeignService {

    //    添加服务降级处理方法
    @Override
    public String getUser(int id) {
        return "error getUser";
    }

    @Override
    public String home(String name) {
        return "error home Method";
    }
}

  在application.yml中配置feign相关配置项

#服务启动端口号
server:
  port: 8763
#服务名称
spring:
  application:
    name: order-demo

#服务注册到eureka服务端地址
eureka:
  instance:
    prefer-ip-address: true
  #    instance-id: 127.0.0.1:${server.port}
  #    hostname: localhost
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
    register-with-eureka: true
    fetch-registry: true

feign:
  hystrix:
    enabled: true #允许开启hystrix功能
  compression:
    request:
      enabled: true #开启请求压缩
      mime-types: text/html,application/xml,application/json # 设置压缩的数据类型
      min-request-size: 2048 # 设置触发压缩的大小下限
    response:
      enabled: true #开启响应压缩
  client:
    config:
      default:
        connectTimeout: 10000   #连接超时时间(ms)
        readTimeout: 10000      # 通信超时时间(ms)

#ribbon:
#  ConnectTimeout: 5000 # 连接超时时间(ms)
#  ReadTimeout: 5000 # 通信超时时间(ms)
#  OkToRetryOnAllOperations: true # 是否对所有操作重试
#  MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数
#  MaxAutoRetries: 1 # 同一实例的重试次数

 

 网关gateway

新建一个网关服务

 在pom中需要加入对应依赖

<!-- 引入gateway网关依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <!--  添加eureka注册中心客户端依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <!-- 添加熔断依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

        <!-- 监控中心 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

  网关的重点在yml配置文件中,

server:
  port: 8081

spring:
  application:
    name: hsdd-gateway
  cloud:
    gateway:
      discovery:
        locator:
          ##gateway开启服务注册和发现的功能
          enabled: true
          ##将请求路径上的服务名配置为小写
          lower-case-service-id: true

#eureka注册地址
eureka:
  instance:
    prefer-ip-address: true
    instance-id: 127.0.0.1:${server.port}
    hostname: localhost
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

logging:
  level:
    org.springframework.cloud.gateway: debug
    org.springframework.http.server.reactive: debug
    org.springframework.web.reactive: debug
    reactor.ipc.netty: debug

feign:
  hystrix:
    enabled: true

  

spring:
  cloud:
    gateway:
      routes:
      - id: test
        uri: http://www.ityouknow.com/springcloud
        predicates:
        - Path=/user/**

  以上两种方式都可以进行网关配置。第一种时自动发现注册服务,服务名为你自己命名的微服务名称

第二种,需要手动配置,在Path中配置上关键字,uri为对应的服务名

原文地址:https://www.cnblogs.com/salmonLeeson/p/11881093.html