Spring Cloud Netflix微服务开发(一) - 服

2019-08-13  本文已影响0人  ElliotG

1. Spring Cloud版本系列

1-1) 常用版本列表

image.png

1-2) 各版本和Spring Boot版本对应表

image.png

(ps: 笔者在教程中使用的版本是Finchley RELEASE + Spring Boot 2.0.4 RELEASE)

 

2. 什么是服务发现

在整个微服务的架构中,服务发现组件是一个非常关键的组件。

 

3. 常用的服务发现组件

3-1) Eureka (Netflix)

3-2) Consul (HashiCorp)

 

4. 实现一个简单的Eureka Server

4-1) 添加netflix依赖

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

4-2) 添加Spring Cloud依赖

由于其本身也是一个Spring Cloud项目,所以这个依赖也是少不了的

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>Finchley.RELEASE</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

4-3) 服务配置

applicaiton.yml

server:
  port: 8761                    # 指定该Eureka实例的端口
eureka:
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

4-4) 程序入口

EurekaApplication.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

/**
 * 使用Eureka做服务发现.
 * @author KG
 */
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
  public static void main(String[] args) {
    SpringApplication.run(EurekaApplication.class, args);
  }
}

 

5. 实现一个简单的服务提供者

5-1) 创建用户实体类

User.java

@Entity
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;
  @Column
  private String username;
  @Column
  private String name;
  @Column
  private Integer age;
  @Column
  private BigDecimal balance;

  // get & set

  ...
}

5-2) 创建数据访问repository(使用spring data jpa

UserRepository.java

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

5-3)创建controller并注入repository

UserController.java

@RestController
@RequestMapping("/user")
public class UserController {
  @Autowired
  private UserRepository userRepository;

  @ApiOperation(value = "Find User by Id")
  @GetMapping("/{id}")
  public @ResponseBody
  User findById(@PathVariable Long id) {
    User user = this.userRepository.findById(id).orElse(null);
    return user;
  }
}

5-4) 配置客户端

为了方便起见,我们使用嵌入式的H2数据库

application.yml

server:
  port: 8000
spring:
  application:
    name: microservice-provider-user
  jpa:
    generate-ddl: true
    show-sql: true
    hibernate:
      ddl-auto: update
  datasource:                           # 指定数据源
    url: jdbc:h2:mem:dbtest
    platform: h2                        # 指定数据源类型
    schema: classpath:schema.sql        # 指定h2数据库的建表脚本
    data: classpath:data.sql            # 指定h2数据库的数据脚本
    username: sa
    password: sa
    driver-class-name: org.h2.Driver
logging:                                # 配置日志级别,让hibernate打印出执行的SQL
  level:
    root: INFO
    org.hibernate: INFO
    org.hibernate.type.descriptor.sql.BasicBinder: TRACE
    org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

这里需要特别注意的事我们把服务注册到先前我们启动的eureka server上去

为了方便起见,我们配置了swagger

SwaggerConfig.java

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("youpackage.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("demo API")
                .description("swagger-ui API for KG demo")
                .termsOfServiceUrl("http://www.genesis.com")
                .contact("genesis")
                .version("1.0")
                .build();
    }
}

5-5) 程序入口

ProviderUserApplication.java

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

程序运行结果:

Eureka

image.png

接口运行

image.png

本文的github代码地址:

Eureka

https://github.com/davidgjy/springcloud-learn/tree/master/discover/microservice-discovery-eureka

User Provider Service

https://github.com/davidgjy/springcloud-learn/tree/master/1_basic/microservice-provider-user

上一篇下一篇

猜你喜欢

热点阅读