介绍

Spring Boot 的核心:约定优于配置

Spring Boot Starters 基于约定优于配置的理念来设计,Spring Boot Starter 中有两个核心组件:自动配置代码和提供自动配置模块及其它有用的依赖。也就意味着当我们项目中引入某个 Starter,即拥有了此软件的默认使用能力,除非我们需要特定的配置,一般情况下我仅需要少量的配置或者不配置即可使用组件对应的功能。

spring boot的优点:
1. 自动装配

Spring Boot 会根据某些规则对所有配置的 Bean 进行初始化。可以减少了很多重复性的工作。比如使用 MongoDB 时,只需要在 pom.xml 中加入 MongoDB 的 Starter 包,然后配置 MongoDB 的连接信息,就可以直接使用 MongoTemplate 自动装配来操作数据库了。

2. 内嵌容器

Spring Boot 应用程序可以不用部署到外部容器中,比如 Tomcat。Spring Boot 应用程序可以直接通过 Maven 命令编译成可执行的 jar 包,通过 java-jar 命令启动即可,非常方便。

3. 应用监控

Spring Boot 中自带监控功能 Actuator,可以实现对程序内部运行情况进行监控,比如 Bean 加载情况、环境变量、日志信息、线程信息等。当然也可以自定义跟业务相关的监控,通过 Actuator 的端点信息进行暴露。

4. Starter 包简化框架集成难度

将 Bean 的自动装配逻辑封装在 Starter 包内部,同时也简化了 Maven Jar 包的依赖,对框架的集成只需要加入一个 Starter 包的配置,降低了烦琐配置的出错几率。

Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的开发便利性巧妙地简化了分布式系统基础设施的开发。服务发现注册、配置中心、消息总线、负载均衡、断路器、数据监控等,都可以用 Spring Boot 的开发风格做到一键启动和部署。

Spring Cloud 是为了解决微服务架构中服务治理而提供的具备一系列功能的开发框架,并且 Spring Cloud 是完全基于 Spring Boot 而开发,Spring Cloud 利用 Spring Boot 特性整合了开源行业中优秀的组件,整体对外提供了一套在微服务架构中服务治理的解决方案。

传参

@RequestMapping(name="/getUser", method= RequestMethod.POST)
public String getUser(User user) {
    ...
}
@RequestMapping(value="get/{name}", method=RequestMethod.GET)
public String get(@PathVariable String name) {
    return name;
}

Spring Boot 的参数校验依赖于 hibernate-validator 来进行。使用 Hibernate Validator 校验数据,需要定义一个接收的数据模型,使用注解的形式描述字段校验的规则

@RequestMapping("/saveUser")
public void saveUser(@Valid User user,BindingResult result) {
    System.out.println("user:"+user);
    if(result.hasErrors()) {
        List<ObjectError> list = result.getAllErrors();
        for (ObjectError error : list) {
            System.out.println(error.getCode()+ "-" + error.getDefaultMessage());
        }
    }
}
public class User {
    @NotEmpty(message="姓名不能为空")
    private String name;
    @Max(value = 100, message = "年龄不能大于100岁")
    @Min(value= 18 ,message= "必须年满18岁!" )
    private int age;
    @NotEmpty(message="密码不能为空")
    @Length(min=6,message="密码长度不能小于6位")
    private String pass;
    //...
}

读取配置

在 Spring Boot 中获取配置属性值的方式有三种:

  1. @value 注解
  2. @ConfigurationProperties
  3. Environment
@Value("${neo.title:lala}")
private String title;
  • @Value("${neo.title}") 会默认读取 application.properties 或者 application.yml 文件中的 neo.title 配置属性值,并赋值给 title。冒号后面是在无值的情况下给的默认值,避免没配置值的报错问题。

使用对象来接收配置项

@Component
@ConfigurationProperties(prefix="neo")
public class NeoProperties {
    private String title;
    private String description;

    //省略getter settet方法
}
  • @Component 的定义为实例,方便在 Spring Boot 项目中引用;
  • @ConfigurationProperties 作用在类上,用于注入 Bean 属性,然后再通过当前 Bean 获取注入值。
  • @ConfigurationProperties(prefix="neo"),表示以 neo 开头的属性会自动赋值到对象的属性中,比如,neo.title 会自动赋值到对象属性 title 中。
    @Autowired
    private Environment environment;

    @GetMapping("config")
    public String getConfig(){
        return environment.getProperty("spring.name");
    }

通过注入获取 Environment 对象,然后再获取定义在配置文件的属性值。

另外可以给测试环境、研发环境设置不同的配置:
application-test.properties
server.port=9999

application-dev.properties
server.port=6666

application.properties
spring.profiles.active=dev

定义starter

Starter 可以说是 Spring Boot 的一个核心功能。

我们知道,当我们搭建一个项目的时候,我们需要依赖很多的 jar 包,即使使用的 Maven 我们也还是需要在 pom.xml 中写入很多的 XML 来引入 jar 包。

Starter 的出现,改变了现状,我们只要在 xml 中引入相关的 Starter 就行。但是并非说我们不需要引入别的 jar 包,只是我们通过了 Starter 自动配置我们需要的相关 jar 包,Starter 相当于个开关或是启动器,当我们引入的时候,就相当于打开或者启动了跟我们引入的 Starter 相关 jar 包的自动配置,而不需要我们在一个个的自己去写引入。

Spring Boot Admin监控

Spring Boot Admin 是一个开源的 Web 项目,用于管理和监控 Spring Boot 应用程序的运行状态。在 Spring Boot 项目中可以通过集成 Spring Boot Admin Client 向 Spring Boot Admin Server 进行注册,这样我们就可以在 Spring Boot Admin Server 统一管理 Spring Boot 应用。

Spring Boot Admin 的主要功能点:

  • 显示健康状况
  • 显示细节
  • 显示生成信息号
  • 跟踪并下载日志文件
  • 查看 JVM 系统 & 环境属性
  • 查看 Spring Boot 配置属性
  • 支持 Spring Cloud 的 postable/env-&/ 刷新端点
  • 简单的日志级管理
  • 与 jmx-bean 交互
  • 查看线程转储
  • 查看 HTTP 跟踪
  • 查看审计事件
  • 查看 HTTP 端点
  • 查看计划任务
  • 查看和删除活动会话(使用 Spring 会话)
  • 查看天桥/Liquibase 数据库迁移
  • 下载堆转储
  • 关于状态更改的通知(通过电子邮件、Sack、Hipchat)
  • 状态更改事件日志(非持久性)

使用第一步加依赖

<dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>${spring-boot-admin.version}</version>
        </dependency>

配置文件 application.yml:

spring:
  application:
    name: admin-server
server:
  port: 9999

设置启动类

@SpringBootApplication
@EnableAdminServer
public class AdminServerApplication {

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

}

接下来我们创建一个 Admin-Client 项目,用来向 Spring-Boot-Admin 注册服务或者实例,我们需要在 pom.xml 文件中引用 spring-boot-admin-starter-client 的依赖。然后我们需要在启配置文件指定 Spring-Boot-Admin 的服务地址,最后启用 Admin-Client。

<dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
            <version>2.1.0</version>
        </dependency>
spring:
  application:
    name: admin-client
  boot:
    admin:
      client:
        url: http://localhost:9999
server:
  port: 8888

management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: ALWAYS

MongoDB使用

MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。
安装可以参照这个博客的文章:https://www.cnblogs.com/zhoul...
image
启动:net start MongoDB
停止:net stop MongoDB
可视化工具:Robo 3T
插入数据:

db.getCollection('performer').insertOne({'name':'小安','sex':'man','age':19})

插入多个使用insertMany
查询:

db.getCollection('performer').find({})
db.getCollection('performer').find({'age':20,'sex':'woman'})
大于等于 : gte
少于等于 : lte
大于     : gt
少于     : lt
不等于   : ne
查询21>年龄<25且名字不等于"zhangsan"的数据
db.getCollection('performer').find({'age':{'$lt':25,'$gt':21},'name':{'$ne','zhangsan'}})
查询数据但不返回列story,age
db.getCollection('performer').find({},{'story':0,'age':0}) 
# 查询数据只返回列 name, age,但不返回object_id
db.getCollection('performer').find({},{'name':1,'age':1,'_id':0}).limit(5)
# 查询年龄大于21岁的个数
# 类似关系型数据库:" select count(*) from performer where age > 21 "
db.getCollection('performer').find({'age':{'$gt':21}}).count()

# 限定返回3条数据
# 类似关系型数据库:" select * from performer where rownmum <=3 "
db.getCollection('performer').find({}).limit(3)

# 对查询年龄少于24的结果进行倒序排序
# 类似关系型数据库:" select * from performer where age < 21 order by age desc "
db.getCollection('performer').find({'age':{'$lt':24}}).sort({'age':-1})
# 类似关系型数据库:" update performer set age = 100 where name ='张益达' "
db.getCollection('performer').updateOne({'name':'张益达'},{'$set':{'age':100}})
一次更新多个
db.getCollection('performer').updateMany({'story':'爱情公寓'},{'$set':{'story':'爱情公寓1-5','best_wishes':'感谢陪伴,赞!'}})
删除一个
db.getCollection('performer').deleteOne({'name':'小安'})
删除多个
db.getCollection('performer').deleteMany({'sex':'man'})

Redis使用

Redis是一个开源的、基于内存的数据结构存储器,可以用作数据库、缓存和消息中间件。
Redis特性

  • 基于内存运行,性能高效
  • 支持分布式,理论上可以无限扩展
  • key-value存储系统
  • 开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API

Redis 的应用场景包括:缓存系统(“热点”数据:高频读、低频写)、计数器、消息队列系统、排行榜、社交网络和实时系统。

Redis有以下5种数据类型

  • String(字符串)
  • Hash(哈希)
  • List(列表)
  • Set(集合)
  • Zset(Sorted Set:有序集合)

Redis 的优势包括它的速度、对富数据类型的支持、操作的原子性,以及通用性:

  • 性能极高,它每秒可执行约 100,000 个 Set 以及约 100,000 个 Get 操作;
  • 丰富的数据类型,Redis 对大多数开发人员已知的大多数数据类型提供了原生支持,这使得各种问题得以轻松解决;
  • 原子性,因为所有 Redis 操作都是原子性的,所以多个客户端会并发地访问一个 Redis 服务器,获取相同的更新值;
  • 丰富的特性,Redis 是一个多效用工具,有非常多的应用场景,包括缓存、消息队列(Redis 原生支持发布/订阅)、短期应用程序数据(比如 Web 会话、Web 页面命中计数)等。

使用方法参照网页:https://segmentfault.com/a/11...

Mybatis连接

首先加入依赖

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>
<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.3.2</version>
</dependency>

修改application.properties代码

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf-8&&useSSL=false
spring.datasource.username=root
spring.datasource.password=12345a
mybatis.mapper-location=classpath:mapping/*.xml

在resources下新建generator文件夹,再新建generatorConfig.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
 <classPathEntry location="E:mavenrepomysqlmysql-connector-java5.1.38mysql-connector-java-5.1.38.jar" />
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
 <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接URL,用户名、密码 -->
 <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/springboot" userId="root" password="12345a">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
 <javaModelGenerator targetPackage="com.example.demo.po" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
 <sqlMapGenerator targetPackage="mappers" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置-->
 <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.mappers" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
 <table tableName="users" domainObjectName="Users" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

新建maven命令
执行:mybatis-generator:generate -e
image
会自动生成mapper、po等文件


stray
132 声望10 粉丝

« 上一篇
react(杂记)
下一篇 »
es6(杂记)