一、数据访问(SQL)

1、数据源的自动配置-HikariDataSource

1、导入JDBC场景

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

数据库版本和驱动版本对应

默认版本:<mysql.version>8.0.22</mysql.version>

        <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!-- <version>5.1.49</version>-->
</dependency>
想要修改版本
1、直接依赖引入具体版本(maven的就近依赖原则)
2、重新声明版本(maven的属性的就近优先原则)
<properties>
<java.version>1.8</java.version>
<mysql.version>5.1.49</mysql.version>
</properties>

2、分析自动配置

1、自动配置的类

  • DataSourceAutoConfiguration : 数据源的自动配置

    • 修改数据源相关的配置:spring.datasource
    • 数据库连接池的配置,是自己容器中没有DataSource才自动配置的
    • 底层配置好的连接池是:HikariDataSource
  • DataSourceTransactionManagerAutoConfiguration: 事务管理器的自动配置

  • JdbcTemplateAutoConfiguration: JdbcTemplate的自动配置,可以来对数据库进行crud

    • 可以修改这个配置项@ConfigurationProperties(prefix = "spring.jdbc") 来修改JdbcTemplate
    • @Bean@Primary JdbcTemplate;容器中有这个组件
  • JndiDataSourceAutoConfiguration: jndi的自动配置

  • XADataSourceAutoConfiguration: 分布式事务相关的

3、修改配置项

spring:
datasource:
url: jdbc:mysql://localhost:3306/db_account
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver

4、测试

@Slf4j
@SpringBootTest
class Boot01WebAdminApplicationTests { //自动注入jdbcTemplate
@Autowired
JdbcTemplate jdbcTemplate; @Test
void contextLoads() {
Long aLong = jdbcTemplate.queryForObject("select count(*) from item", Long.class);
log.info("查询数量为:{}",aLong);
} }

2、使用Druid数据源

1、druid官方github地址

https://github.com/alibaba/druid

整合第三方技术的两种方式

  • 自定义
  • 找starter

2、自定义方式

3、使用官方stater方式

1、引入druid-starter

        <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>

2、分析自动配置

  • 扩展配置项 spring.datasource.druid

  • DruidSpringAopConfiguration.class, 监控SpringBean的;配置项:spring.datasource.druid.aop-patterns

  • DruidStatViewServletConfiguration.class, 监控页的配置:spring.datasource.druid.stat-view-servlet;默认开启

  • DruidWebStatFilterConfiguration.class, web监控配置;spring.datasource.druid.web-stat-filter;默认开启

  • DruidFilterConfiguration.class}) 所有Druid自己filter的配置

3、配置示例

spring:
datasource:
url: jdbc:mysql://localhost:3306/db_account
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver druid:
aop-patterns: com.atguigu.admin.* #监控SpringBean
filters: stat,wall # 底层开启功能,stat(sql监控),wall(防火墙) stat-view-servlet: # 配置监控页功能
enabled: true
login-username: admin
login-password: admin
resetEnable: false web-stat-filter: # 监控web
enabled: true
urlPattern: /*
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*' filter:
stat: # 对上面filters里面的stat的详细配置
slow-sql-millis: 1000
logSlowSql: true
enabled: true
wall:
enabled: true
config:
drop-table-allow: false

SpringBoot配置示例

https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

配置项列表https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8

4、监控页

http://localhost:8080/druid/进入数据源的监控页

3、整合Mybatis操作

0、导入mybatis的依赖

 <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>

1、编写Mapper接口(添加@mapper注解)

package gyb.boot01webadmin.mapper;
import org.apache.ibatis.annotations.Mapper; @Mapper
public interface ItemMapper {
/**
* 查询item的数量
* @return
*/ Long SumItemNum();
}

1、编写mabatis全局配置文件

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    </configuration>

2、编写映射文件

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--配置mapper,和命名空间--><mapper namespace="gyb.boot01webadmin.mapper.ItemMapper">    <select id="SumItemNum" resultType="Long">        select count(*) from item    </select></mapper>

3、编写yaml中的mybatis相关配置

mybatis:  #  config-location: classpath:mybatis/mybatis-config.xml  mapper-locations: classpath:mybatis/mapper/*.xml  configuration:  #开启驼峰命名法    map-underscore-to-camel-case: true

4、测试

@AutowiredItemService itemService;@GetMapping("/db")@ResponseBodypublic String dbTest(){    Long num = itemService.SumItemNum();    return num.toString();}

5、注解模式

@Mapperpublic interface CityMapper {    @Select("select * from city where id=#{id}")    @Options(useGeneratedKeys= true, keyProperty=id)    public City getById(Long id);    public void insert(City city);}

6、tip: 获取自增主键

​ insert ... .. ... .

4、整合 MyBatis-Plus 完成CRUD

1、什么是MyBatis-Plus

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

mybatis plus 官网

建议安装 MybatisX 插件

2、开发步骤

1、导入依赖

导入后不需要导入mybatis-spring的依赖

<dependency>    <groupId>com.baomidou</groupId>    <artifactId>mybatis-plus-boot-starter</artifactId>    <version>3.4.1</version></dependency>

2、配置数据库

spring:  datasource:    url: jdbc:mysql://localhost:3306/db_account    username: root    password: 123456    driver-class-name: com.mysql.jdbc.Driver        druid:      aop-patterns: com.atguigu.admin.*  #监控SpringBean      filters: stat,wall     # 底层开启功能,stat(sql监控),wall(防火墙)      stat-view-servlet:   # 配置监控页功能        enabled: true        login-username: admin        login-password: admin        resetEnable: false      web-stat-filter:  # 监控web        enabled: true        urlPattern: /*        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'      filter:        stat:    # 对上面filters里面的stat的详细配置          slow-sql-millis: 1000          logSlowSql: true          enabled: true        wall:          enabled: true          config:            drop-table-allow: false

3、在在 Spring Boot 启动类中添加 @MapperScan 注解

扫描 Mapper 文件夹:

@MapperScan("gyb.mapper")

4、编写实体类、Mapper接口(继承)

@TableField(exist = false):去除表中不存在的字段

@Data//使用Mybatis时,实体类的属性都应存在于数据库public class User {    //注解表示此属性不存在数据库的字段与之对应    @TableField(exist = false)    private String username;    @TableField(exist = false)    private String password;    private Long id;    private String name;    private Integer age;    private String email;}

继承BaseMapper<>泛型为要映射的对象

public interface UserMapper extends BaseMapper<User> {}

5、测试

@Testvoid MybatisPlusTest(){    //User user = userMapper.selectById(1);    List<User> users = userMapper.selectList(null);    for (User user : users) {        log.info(String.valueOf(user));    }}

6、ServiceImpl使用提供好的接口

UserService需要继承IService

UserServiceImpl 继承实现类extends ServiceImpl<UserMapper,User>

@Servicepublic class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {}public interface UserService extends IService<User> {}

在controller中:

userServie.函数名

二、NoSQL

Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。

1、Redis自动配置

        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-redis</artifactId>        </dependency>

自动配置:

  • RedisAutoConfiguration 自动配置类。RedisProperties 属性类 --> spring.redis.xxx是对redis的配置
  • 连接工厂是准备好的。LettuceConnectionConfiguration、JedisConnectionConfiguration
  • 自动注入了RedisTemplate<Object, Object> : xxxTemplate;
  • 自动注入了StringRedisTemplate;k:v都是String
  • key:value
  • 底层只要我们使用 StringRedisTemplate、****RedisTemplate就可以操作redis

redis环境搭建

1、阿里云按量付费redis。经典网络

2、申请redis的公网连接地址

3、修改白名单 允许0.0.0.0/0 访问

2、RedisTemplate与Lettuce

    @Test    void testRedis(){        ValueOperations<String, String> operations = redisTemplate.opsForValue();        operations.set("hello","world");        String hello = operations.get("hello");        System.out.println(hello);    }

3、切换至jedis

        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-redis</artifactId>        </dependency><!--        导入jedis-->        <dependency>            <groupId>redis.clients</groupId>            <artifactId>jedis</artifactId>        </dependency>spring:  redis:      host: r-bp1nc7reqesxisgxpipd.redis.rds.aliyuncs.com      port: 6379      password: lfy:Lfy123456      client-type: jedis      jedis:        pool:          max-active: 10

SpringBoot笔记(6)的更多相关文章

  1. SpringBoot笔记十六:ElasticSearch

    目录 ElasticSearch官方文档 ElasticSearch安装 ElasticSearch简介 ElasticSearch操作数据,RESTful风格 存储 检查是否存在 删除 查询 更新 ...

  2. SpringBoot笔记一

    1 开始 1.1 spring介绍 Spring Boot使开发独立的,产品级别的基于Spring的应用变得非常简单,你只需"just run". 我们为Spring平台及第三方库 ...

  3. 【SpringBoot笔记】SpringBoot整合Druid数据连接池

    废话少说,按SpringBoot的老套路来. [step1]:添加依赖 <!-- 数据库连接池 --> <dependency> <groupId>com.alib ...

  4. SpringBoot笔记十七:热部署

    目录 什么是热部署 Devtools热部署 什么是热部署 热部署,就是在应用正在运行的时候升级软件,却不需要重新启动应用. 举个例子,王者荣耀的更新有时候就是热部署,热更新,就是他提示你更新,更新40 ...

  5. SpringBoot笔记十四:消息队列

    目录 什么是消息队列 消息队列的作用 异步通信 应用解耦 流量削峰 RabbitMQ RabbitMQ流程简介 RabbitMQ的三种模式 安装RabbitMQ RabbitMQ交换器路由和队列的创建 ...

  6. SpringBoot笔记十三:引入webjar资源和国际化处理

    目录 什么是webjar 怎么使用webjar 国际化 新建国际化配置文件 配置配置文件 使用配置文件 我们先来看一个html,带有css的,我们就以这个为准来讲解. 资源可以去我网盘下载 链接:ht ...

  7. springboot笔记1(转载于puresmile)

    构建微服务:Spring boot 入门篇 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框 ...

  8. SpringBoot笔记

    官网: http://springboot.fun/ 收集到一个比较全的: https://blog.csdn.net/xiaoyu411502/article/details/52474037 Id ...

  9. springboot笔记05——profile多环境配置切换

    前言 一个应用程序从开发到上线,往往需要经历几个阶段,例如开发.测试.上线.每个阶段所用到的环境的配置可能都是不一样的,Springboot 应用可以很方便地在各个环境中对配置进行切换.所以,今天主要 ...

  10. springboot笔记09——使用aop

    什么是AOP? aop(Aspect Oriented Programming)面向切面编程,是OOP(Object-Oriented Programing,面向对象编程)的补充和完善.OOP引入封装 ...

随机推荐

  1. MySQL架构及优化原理

    1 MySQL架构原理 1.1 MySQL架构原理参看下述链接: https://blog.csdn.net/hguisu/article/details/7106342 1.2 MySQL优化详解参 ...

  2. python3中的缺省参数和global

    关于py中缺省参数: 在声明函数的时候对某些参数(一个或多个)进行赋值,在你调用的时候无需在实参列表中体现该参数,但是在执行的时候会默认加上这个已经在形参中定义好的参数. 但是,缺省参数必须放在最后, ...

  3. Input 只能输入正数以及2位小数点

    <input onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d ...

  4. 使用scrapy搭建大型爬虫系统

    最近新项目准备启动,在开始前内容.词库这些都需要提前做好准备,所以就有了这篇文章.在开始动手,看了下行业核心词排在首页的站,发现内容都多得不要不要的,各种乱七八糟的频道.页面模板,心想,如果每个网站. ...

  5. postman之get请求

    get请求:

  6. MapReduce框架原理-InputFormat数据输入

    InputFormat简介 InputFormat:管控MR程序文件输入到Mapper阶段,主要做两项操作:怎么去切片?怎么将切片数据转换成键值对数据. InputFormat是一个抽象类,没有实现怎 ...

  7. 『Java』成员内部类 匿名内部类

    成员内部类 成员方法类是定义在一个类中的方法外的类,例如: public class Outer{ // 外部类 class Inner { // 内部类 // 内部类成员 } // 外部类成员 } ...

  8. 5、Python断言及常用断言函数总结

    Python断言 Python assert 语句,又称断言语句,可以看做是功能缩小版的 if 语句,它用于判断某个表达式的值,如果值为真,则程序可以继续往下执行:反之,Python 解释器会报 As ...

  9. MySQL高级查询 & 事务机制

    1.基础查询where 高级条件查询Where子句 SELECT empno,ename,sal,hiredate FROM t_tmp WHERE deptno=10 AND (sal+IFNULL ...

  10. Longhorn 企业级云原生分布式容器存储-券(Volume)和节点(Node)

    内容来源于官方 Longhorn 1.1.2 英文技术手册. 系列 Longhorn 是什么? Longhorn 云原生分布式块存储解决方案设计架构和概念 Longhorn 企业级云原生容器存储解决方 ...