前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在Spring Boot和Gradle项目中设置微服务架构的基础知识

在Spring Boot和Gradle项目中设置微服务架构的基础知识

作者头像
February
修改2018-11-23 14:17:32
1.4K0
修改2018-11-23 14:17:32
举报
文章被收录于专栏:技术翻译技术翻译

微服务,也被称为微服务架构,是一种建筑风格,结构的应用程序的松散耦合的服务,实现业务功能的集合。微服务架构支持大型复杂应用程序的持续交付/部署,并允许组织发展其技术堆栈。它的主要优点是与部署一起扩展。下面您将找到使用微服务架构构建的简单Web应用程序的基本要素。

1.Spring Boot

Spring Boot可以轻松创建安装了tomcat的独立应用程序,您可以通过启动jar文件来运行它。Spring Boot应用程序不需要任何类型的XML配置; 一切都只使用注释完成。使用Spring Boot创建Web应用程序非常简单。下面,您可以看到一个Spring Boot控制器的示例,这使得使用REST服务创建Web应用程序非常简单:

代码语言:javascript
复制
@Controller
@EnableAutoConfiguration
public class SampleController {
    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}

2. Gradle

Gradle是一个类似于Maven和Ant的Java构建工具。Gradle比两者都强大,因为它是Maven和Ant的组合。Gradle不需要任何XML文件,因为它有自己的基于Groovy的DSL。Gradle比Maven或Ant简单明了。我们有build.gradle文件,其中包含Web应用程序所需的所有依赖项。它还包括要与Java,Hibernate和Database版本一起生成的jar名称。以下是build.gradle文件中的代码段:

代码语言:javascript
复制
apply plugin: 'java'
apply plugin: 'checkstyle'
apply plugin: 'findbugs'
apply plugin: 'pmd'
version = '1.0'
repositories {
    mavenCentral()
}
dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    testCompile group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3'
}

3. Discovery Server

Discovery Server主要用于将所有微服务客户端连接在一个中心位置,以便它们可以轻松通信。Eureka Discovery从属于服务的每个实例接收心跳消息。如果心跳故障超过可配置的时间表,则通常会从注册表中删除该实例。通过拥有 @EnableDiscoveryClient, 您可以在Spring Boot应用程序中轻松创建发现客户端。

代码语言:javascript
复制
@SpringBootApplication
@EnableEurekaServer
@EnableDiscoveryClient
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}

对于所有发现客户端,您需要将以下配置添加到每个客户端模块的application.yml中以找到其发现服务器:

代码语言:javascript
复制
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

4. Central Config Server

拥有central-config-server的主要功能是在中央位置存储所有类型的配置属性,这样我们就不需要明确地去每个核心模块来更改属性。它实际上连接到发现服务器,这使得每个核心的微服务都可以轻松获取其属性文件。每当对属性文件进行更改时,我们都可以重新启动此服务器以及其属性文件已更改的核心模块; 您甚至不需要任何类型的核心模块构建来获取更新的属性。您将属性文件放在任何特定位置(Git等),并在application.yml文件中指定属性的路径。下面的代码片段将为您提供Central Config服务器的概述:

代码语言:javascript
复制
@SpringBootApplication
@EnableConfigServer
@EnableDiscoveryClient
public class CentralConfigServerApplication {
 public static void main(String[] args) {
  SpringApplication.run(CentralConfigServerApplication.class, args);
 }
}xxxxxxxxxx @SpringBootApplication@EnableConfigServer@EnableDiscoveryClientpublic class CentralConfigServerApplication { public static void main(String[] args) {  SpringApplication.run(CentralConfigServerApplication.class, args); }}@SpringBootApplication

application.yml

代码语言:javascript
复制
spring:
    profiles:
        active: native
    cloud:
        config:
            server:
                native:
                    searchLocations: file:./properties,classpath:config/

5. Gateway Server

Gateway / Zuul是一项边缘服务,可提供动态路由,监控,弹性,安全性等。其主要目的是为核心微服务提供安全性和路由。我们可以在网关服务器中使用不同类型的过滤器,以便我们可以管理对核心微服务的任何类型的API调用的安全性。它充当核心微服务和外部应用程序之间的代理。

代码语言:javascript
复制
package com.example.EmployeeZuulService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@EnableZuulProxy
@EnableDiscoveryClient
@SpringBootApplication
public class EmployeeZuulServiceApplication {
   public static void main(String[] args) {
      SpringApplication.run(EmployeeZuulServiceApplication.class, args);
   }
}

application.yml

代码语言:javascript
复制
zuul:
prefix: /application_name
    ignoredServices: "*"
    routes:
    coreservice_name: /coreservice_name/**

6. Orchestra微服务层

在微服务架构中使用这一层是为了结合来自多个核心服务的不同类型的响应,并对数据进行更多处理,然后在响应中发布它们。与所有其他层相比,该层的主要需求较少。它只是一个Spring Boot应用程序,它与发现,网关和微服务进行通信,但没有与数据库部分进行任何类型的交互。

代码语言:javascript
复制
@RestController
@RequestMapping("orchestra")
public class OrchestraController {
  @Autowired
  @LoadBalanced
  protected RestTemplate restTemplate;
  protected Logger LOGGER = LoggerFactory.getLogger(getClass());
  @ApiOperation(value = "Retrieve combined list from two microservices")
  @RequestMapping(value="/combinedlists", method=RequestMethod.GET, produces= MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<List<Object>> getCombinedList(HttpServletRequest request) {
    LOGGER.info("Inside getCombinedList method");
    List<Object> combinedList = new ArrayList<>();
    try {
      String url1 = "http://"+"<core_microservice_name1>"+"rest_api_url1";
      String url2 = "http://"+"<core_microservice_name2>"+"rest_api_url2";
      ResponseEntity<List<Object>> result1 = restTemplate.exchange(url1, HttpMethod.GET, null,new ParameterizedTypeReference<List<Object>>() {});
      ResponseEntity<List<Object>> result2 = restTemplate.exchange(url2, HttpMethod.GET, null,new ParameterizedTypeReference<List<Object>>() {});
      List<Object> list1 = result1.getBody();
      List<Object> list2 = result2.getBody();
      combinedList.addAll(list1);
      combinedList.addAll(list2);
    }
    catch(Exception e) {
      LOGGER.error("Exception in getCombinedList method:",e.getMessage());
      return new ResponseEntity<List<Object>>(combinedList,HttpStatus.INTERNAL_SERVER_ERROR);
    }
    LOGGER.info("Exit from getCombinedList method");
    return new ResponseEntity<List<Object>>(combinedList,HttpStatus.OK);
  }
}

7.核心微服务层

这是微服务架构中的最低层,它实际上对数据库执行大量操作并根据需要处理数据。实际的REST服务是在核心层编写的。这部分执行不同事务的每个操作。

它通过@EnableDiscoveryClient 注释与发现有联系 。由于我们已经在中央配置服务器中添加了环境级别配置,因此我们仍然可以在核心模块本身的application.properties中具有应用程序级配置设置/消息。

SampleServiceApplication.java

代码语言:javascript
复制
@SpringBootApplication
@EnableDiscoveryClient
public class SampleServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(SampleServiceApplication.class, args);
    }
}

SampleServiceController.java

代码语言:javascript
复制
@RestController
public class RecommendationService {
    private static final Logger LOG = LoggerFactory.getLogger(RecommendationService.class);
    @Autowired
    private SetProcTimeBean setProcTimeBean;
    @Autowired
    private LoadBalancerClient loadBalancer;
private RestTemplate restTemplate = new RestTemplate();
    @RequestMapping("/recommendation")
    public List<Recommendation> getRecommendations(@RequestParam(value = "productId",  required = true) int productId) {
        List<Recommendation> list = new ArrayList<>();
        list.add(new Recommendation(productId, 1, "Author 1", 1, "Content 1"));
        list.add(new Recommendation(productId, 2, "Author 2", 2, "Content 2"));
        list.add(new Recommendation(productId, 3, "Author 3", 3, "Content 3"));
        return list;
    }
}

application.yml

代码语言:javascript
复制
server:
  port: 7878
eureka:
  instance:
    leaseRenewalIntervalInSeconds: 10
    metadataMap:
      instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${random.value}}}
  client:
    registryFetchIntervalSeconds: 5

bootstrap.yml

代码语言:javascript
复制
spring:
  application:
    name: sample
  cloud:
    config:
      enabled: true
      discovery:
        enabled: true
        serviceId: central-config-server

原文标题《Basics for Setting Up a Microservices Architecture in a Project for Spring Boot and Gradle》

作者:Akash Bhingole

译者:February

不代表云加社区观点,更多详情请查看原文链接

本文系外文翻译,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系外文翻译前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 2. Gradle
  • 3. Discovery Server
  • 4. Central Config Server
  • 5. Gateway Server
  • 6. Orchestra微服务层
  • 7.核心微服务层
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档