Spring系列

376 阅读2分钟

Spring Core

IOC有什么好处

IOC的核心思想是将资源的创建和使用交给第三方管理,这样带来了两个好处

  1. 资源统一管理,增强了可配置和易管理
  2. 解耦了使用方和资源方的依赖程度,隐藏了资源方的实现细节

注入的方式

总体上分为

  1. xml方式分为构造器注入,setter注入
  2. 注解分为构造器注入,setter注入,字段注入

为什么不推荐字段注入

  • 会导致组件与IoC容器紧耦合(这是最重要的原因,离开了IoC容器去使用组件,在注入依赖时就会十分困难),比如单元测试
  • 依赖对外部不可见,外界可以看到构造器和setter,但无法看到私有字段,自然无法了解所需依赖
  • 不能像构造器那样注入不可变的对象,字段不能加final
  • 依赖过多时不够明显,比如我需要10个依赖,用构造器注入就会显得庞大,这时候应该考虑一下此组件是不是违反了单一职责原则






Spring Cloud微服务解决方案初探

毕业版本依赖关系

Spring Cloud Version Spring Cloud Alibaba Version Spring Boot Version
Spring Cloud Hoxton.SR3 2.2.1.RELEASE 2.2.5.RELEASE
Spring Cloud Hoxton.RELEASE 2.2.0.RELEASE 2.2.X.RELEASE
Spring Cloud Greenwich 2.1.2.RELEASE 2.1.X.RELEASE
Spring Cloud Finchley 2.0.2.RELEASE 2.0.X.RELEASE
Spring Cloud Edgware 1.5.1.RELEASE 1.5.X.RELEASE

Nocas

Nacos 支持几乎所有主流类型的“服务”的发现、配置和管理

Spring Cloud 集成Nacos

安装

 tar -xvf nacos-server-$version.tar.gz
sh startup.sh -m standalone      standalone代表着单机模式运行

作为配置中心的用法

  • pom文件配置
 <dependencies>
 <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.1.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
  • yml文件中配置
server:
  port: 8086
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.223.130:8848
  application:
    name: test2
  • 在配置类上通过 Spring Cloud 原生注解 @EnableDiscoveryClient 开启服务注册发现功能
@SpringBootApplication
@EnableDiscoveryClient
public class Demo2Application {
    public static void main(String[] args) {
        SpringApplication.run(Demo2Application.class);
    }
}

验证访问 Nacos服务ip:8848/nocas服务配置即出现相应列表

Feign 远程调用

在Nocas中注册两个服务,一个作为调用方demo1,一个作为被调用方demo2

server:
  port: 8085
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.223.130:8848
  application:
    name: demo1
  port: 8086
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.223.130:8848
  application:
    name: demo2
  • 调用方使用xml配置
 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
 </dependency>
  • 被调用方接口
@RestController
@RequestMapping("/demo2")
public class TestController {

    @GetMapping("/test")
    public String  get(){
        return "124";
    }
}
  • 调用方配置 编写接口,在接口上添加@FeignClient,value值是被调用方服务名称,添加被调用方法的方法签名
@FeignClient("test2")
public interface Feign {
    @GetMapping("/demo2/test")
    String get();
}

调用接口

@RestController
@RequestMapping("demo")
public class TestController {
    @Autowired
    Feign feign;
    @GetMapping("get")
    String test(){
        return   feign.get();
    }
}

配置使用Feign客户端

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.demo.test.feign")
public class Demo1Application {
    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class);
    }
}

发送调用方的接口请求,收到被调用方的响应结果

Nacos 作为配置中心

pom文件

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

新建 bootstrap.yml 中配置

spring:
  cloud:
    nacos:
      config:
        server-addr: 192.168.223.130:8848
        file-extension: yaml

编写测试接口,@RefreshScope实现动态刷新,启动程序时,spring会从Nacos的配置中心格式为${prefix}-${spring.profiles.active}.${file-extension}的dataId获取对应的配置变量

  • prefix 默认为 spring.application.name 的值,也可以通过配置项 spring.cloud.nacos.config.prefix来配置。
  • spring.profiles.active 即为当前环境对应的 profile,详情可以参考 Spring Boot文档。 注意:当 spring.profiles.active 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成 prefix.{prefix}.{file-extension}
  • file-exetension 为配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension 来配置。目前只支持 properties 和 yaml 类型。默认是properties
@RestController
@RefreshScope
@RequestMapping("/demo2")
public class TestController {

    @GetMapping("/test")
    public String get() {
        return "123";
    }

    @Value("${user.name}")
    private String name;

    @Value("${user.age}")
    private Integer age;

    @Override
    public String toString() {
        return "TestController{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @GetMapping("user")
    public String user() {
        return toString();
    }
}

由于application.yml 文件配置的spring.application.name=test2,在Nacos首页添加配置

访问

修改配置内容可实现动态获取,无需重启应用(有网络延迟)

网关Spring Cloud Gateway

路由

由一个id,一个url,一组断言集合,一组过滤器集合组成 案例 pom.xml

  <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-gateway</artifactId>
       </dependency>

application.yml

spring:
 cloud:
   gateway:
     routes:
       - id: test1
         uri: https://www.baidu.com
         predicates: #断言规则
           - Query=url, baidu #参数断言(可以是正则表达式):?url=baidu
       - id: test2
         uri: https://www.qq.com
         predicates:
           - Query=url, qq

访问 localhost:8080?url=qq

localhost:8080/aaa?url=qq =====> www.qq.com/aaa