SpringCloud Alibaba组件搭建微服务

650 阅读1分钟

SpringCloud Alibaba组件搭建微服务

1.引入SpringCloud,SpringCloud Alibaba,SpringBoot的pom文件

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-dependencies</artifactId>
    <version>Hoxton.SR7</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.2.RELEASE</version>
</dependency>
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
</dependencyManagement>

2.集成nacos服务注册

 <dependency>
     <groupId>com.alibaba.cloud</groupId>
     <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
 </dependency>
spring:
  application:
    name: 服务名
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848

在启动类上加入此注解@EnableDiscoveryClient,就完成服务注册。


3.集成nacos配置中心

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

新建bootstrap.yml文件

spring:
  application:
    name: 服务名
  config:
    file-extension: yaml #文件后缀
    server-addr: localhost:8848 #nacos地址
    group: TEST_GROUP # 分组,默认就是DEFAULT_GROUP
  profiles:
    active: dev

然后到nacos界面上新建一个文件,Data Id就按照下面的规则

spring.application.name{spring.application.name}-{spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

例如:服务名-dev.yaml

然后到controller类中加入@RefreshScope 注解就可以实现动态刷新配置了

这样就把配置中心进行集成进来了。

4.集成openfeign

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

例如服务A调用服务B

  • 在A的启动类上加入@EnableFeignClients(basePackages = "com.angel.item.mallmember.feignservice")指明扫描的包
  • 定义远程调用接口
@Component
@FeignClient("coupon") // 所调用B服务的服务名称
public interface TestService {
    @GetMapping("/api/mallcoupon/smsmemberprice/info/{id}")
    public APIResponse<Object> info(@PathVariable("id") Long id);
}

这样就把openfeign集成好了。