spring boot 学习笔记(一)

学习连接:http://www.cnblogs.com/ityouknow/category/914493.html

定义

spring boot 是由pivotal 团队提供的权限框架,设计目的是用来简化新的spring应用的初始搭建以及开发过程,该框架使用了特定的方式来进行设置,从而使开发人员不在须要定义样板化的配置。所以,spring boot 不是新的框架,是默认设置了不少框架的使用方式,就像maven 整合了全部的jar包,spring boot 整合了一部分的框架。css

优点

简单,快速,方便html

原有web项目前端

  • 1,配置 web.xml,加载 spring 和springMVC
  • 2,配置数据库链接,配置spring事务
  • 3,配置加载配置文件的读取,开启注解扫描。
  • 4,配置日志文件

学习

  • 热部署 devtools
  • json注解,jsonFromat 等
  • service 配置 port 等
  • config 配置 对照
  • jpa配置 自动生成类等

thymeleaf 模板

thymeleaf (saimei leifu) 介绍

thymeleaf 是一款用于渲染XML/XHTML/HTML5内容的模板模板引擎,相似JSP,velocity,FreeMaker等,它能够轻易的与spring MVC 等Web框架进行集成,做为Web应用的模板引擎。与其余模板引擎相比。thymeleaf 最大的特色是可以直接再浏览器中打开并正确的显示模板页面,而不须要启动整个web应用。 和 velocity ,fremaker,beetle 这类的模板到底好在哪里?thymeleaf是不一样的,由于它使用了天然的模板技术,这觉得着thymeleaf的模板语法不会破坏文档的结构,模板依旧是有效的xml文档,模板还能够做为工做原型,thymeleaf会在运行期替换掉静态值,velocity与freemarker则是连续的文本处理器。vue

  • Velocity:

    $messagejava

  • FreeMarker:

    ${message}mysql

  • Thymeleaf:

    Hello World!web

因为thymeleaf 使用XML DOM 解析器,所以它并不适合处理大规模的XML文件redis

URl

url 在web应用模板中占据十分重要的地位,须要注意的是thymeleaf 对于url的处理是经过语法,@{。。。}来处理的,thymeleaf 支持决定路径。spring

Thymeleafsql

条件求值

<a th:href="@{/login}" th:unless=${session.user != null}>Login

for 循环

<td th:text="${prod.name}">Onions</td> <td th:text="${prod.price}">2.41</td> <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>

页面即原型

在web 开发过程当中,先后端的配合,须要修改模板,静态资源文件等, 但实际上前端工程师的职责更多应该关注与页面非后端,使用jsp,veloctiy 等传统的java模板引擎很那作到这一点,biubiu渲染之后才能看到结果,thymeleaf 从根本上颠覆了这一过程,经过书信进行模板渲染。

过滤器 filter 过滤器

filters用于记录调用日志,排除xss威胁的字符,执行权限验证等。SpringBoot 自动添加OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,咱们也能够自定义filter

1, 实现Filter接口,实现Filter方法。 2, 添加@Configuration 注解,将自定义Filter 加入过滤链

自定义 Property

1,配置在application.properties中 > * com.neo.title=螺旋 * com.meo.description=啰嗦 2,自定义配置类 @Component public class NeoProprtties { @Value private String title; @Value private String description; }

数据库

jpa sun官方提出的java持久化规范,它为java开发人员提供了一种对象/关系映射工具来管理java应用中的关系数据,住哟啊为了简化现有的持久化开发工做和整合prm技术,结束现有的,hibernate,TopLink,JDO等orm框架各自为营局面,吸取了他们的有点,具备
易于使用,伸缩性强的有点。与spring 结合紧密。
> jpa 是一套规范,不是一套产品。hibernate,topLink,JDO 他们是一套产品。

spring data jpa 是spring 基于orm框架,jpa规范基础上封装的一套jpa应用框架,可以使开发者使用简易代码访问数据和操做数据,提供crud的经常使用功能。
 

mysql  ,spring data jpa 是利用Hibernate 生成各类自动化的sql ,crud 等
1,添加java包 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> 2,添加配置文件 > spring.datasource.url=jdbc:mysql://localhost:3306/test

spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql= true

3,hibernate.hbm2ddl.auto 参数的主要用于:自动建立、更新、验证数据库表结构4个值 > * create :每次加载hibernate时都会删除上一次生成的表,而后根据model类从新生成新的表。就是没有改变也会这样执行。会致使数据库文件丢失。 > * create-drop: 每次加载hibernate是根据model类生成表,可是sessionFactory已关闭,表就自动删除。 > * update :最经常使用的,第一次加载hibernate时候根据model类会自动创建表的结构(要有创建好数据库),之后加载hibernate 时根据model 类自动更新表结构,即便表表结构改变了单表中仍然存在不会删除之前的行,要注意的是当部署到服务器后,表接口是不会被立刻创建起来的,是哟啊等应用第一次运行起来才会。 > * validate : 每次加载hibernate时,验证建立数据库结构,只会和数据库中的表进行比较,不会建立新表,可是会插入新值。 dialect 指, 指定生成表名的存储引擎为inneoDB show-sql 是否打印出自动生产的sql。 3,添加实体类和Dao > @Entity

public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @Column(nullable = false, unique = true) private String userName; @Column(nullable = false) private String passWord; @Column(nullable = false, unique = true) private String email; @Column(nullable = true, unique = true) private String nickName; @Column(nullable = false) private String regTime; //省略getter settet方法、构造方法 }

dao 只要继承jpaRepository 类就能够。

public interface UserRepository extends JpaRepository<User, Long> { User findByUserName(String userName); User findByUserNameOrEmail(String username, String email);

entity 中不映射成列的字段须要加 @Transient 不加注解会被映射成列。

多数据源的支持

同源数据库的多源支持

若是使用分布式开发模式,不一样的服务使用不一样的数据库,一个项目中有可能会使用多个数据源。所以须要配置多个数据源,spring data jpa 对多个数据源有很好的支持,实现主要分三步 1,配置多个数据源 2,不一样实体类放入不一样包内 3,声明不一样的包实体类指向不一样的数据源,事务支持。

使用枚举注解

咱们但愿数据库中存储的是枚举对应的String类型,而不是枚举的索引值 @Enumerated(EnumType.STRING) @Column(nullable = true) private UserType type;

4,测试 注解,@RunWith(SpringJunit4ClassRunner.class) @SpringApplicationCinfiguration(Application.class)

spring data jpa 还有不少的功能,好比封装好的分页,能够本身蒂尼sql,主从分离等。

Gradle 构建工具

spring 项目建议使用gradle进行构建项目相对 maven来说,gradle更简洁。 并且 gradle 构建大型项目。吸取了maven和ant的特色。

Werbjars

Webjars 是一个神奇的东西,能够以jar包的形式,使用前端的各类框架,组件。 webjars 是将客户端资源达成jar包。以对资源进行统一的依赖管理。webjar包部署在maven 中央仓库上。

  • 为何使用,webjars 能够像maven同样提供给咱们前端的资源jar包,方便管理依赖。
  • 如何使用 WebJars主官网 查找对于的组件,好比Vuejs <dependency> <groupId>org.webjars.bower</groupId> <artifactId>vue</artifactId> <version>1.0.21</version> </dependency>
  • 页面引入
  • <link th:href="@{/webjars/bootstrap/3.3.6/dist/css/bootstrap.css}" rel="stylesheet"></link>

spring Boot redis 的使用

redis 介绍

redis 是业界使用最普遍的内存数据存储。相比 memcached redis支持更丰富的数据结构。例如,hashes list sets 等,支持数据持久化。redis还提供数据库的一些特性,例如,事务,HA,主从库等。redis 兼具了缓存系统和数据库的一些特性,有丰富的应用场景。

如何使用

  • 引入spring -boot-starter- redis jar包

  • 添加配置文件 # REDIS (RedisProperties) Redis数据库索引(默认为0) spring.redis.database=0
    Redis服务器地址 spring.redis.host=192.168.0.58 Redis服务器链接端口 spring.redis.port=6379
    Redis服务器链接密码(默认为空) spring.redis.password=
    链接池最大链接数(使用负值表示没有限制) spring.redis.pool.max-active=8
    链接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1
    链接池中的最大空闲链接 spring.redis.pool.max-idle=8
    链接池中的最小空闲链接 spring.redis.pool.min-idle=0
    链接超时时间(毫秒) spring.redis.timeout=0

  • 添加cache 配置类 @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport{ }

  • 自动根据方法生成缓存 @RequestMapping("/getUser") @Cacheable(value="user-key") value 值就是缓存到redis中的key

共享Session-spring-session-data-redis

分布式系统中,sessiong共享有不少的解决方案,其中托管到缓存中应该是最经常使用的方案之一,

  • 引入依赖 spring-session-data-redis

  • session配置 @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30) public class SessionConfig { } maxInactiveIntervalInSeconds :设置session失效时间,使用redis session 以后,原boot 的server.session.timeout 属性再也不生效。

spring boot RabbitMQ

介绍

RabbitMQ 是实现高级消息队列,AMQP的消息中间件的一种,起源于金融系统,在分布是系统中存储转发消息,具备易用性,拓展性,高可用的特性,RabbitMQ 主要是觉得系统之间的双向解耦而生,当生产者生成大量数据,消费者没法快速的消费,就须要一个中间件缓冲,保存这些数据。

AMQP,即 Advanced Message Queuing Protocel ,高级消息队列协议。是应用层协议的一个开放版本,为面向消息的中间件设计。消息中间件主要是用于组件之间的解耦,消费发送者无需知道消息执行者者,反之亦然,AMQP 主要特征就是面向消息,队列,路由(包括点对点和发布,订阅),可靠性,安全等特色。 -- 消息中间件主要是用于组件之间的解耦。

RabbitMQ 是一个开源的AMQP实现,服务端使用Erlang 语言编写支持多种客服端,现有的语言基本偶支持。入Python,ruby。net java jms c PHP actionscript xmpp stomp。AJAX。用于在分布式系统中储存转发信息,在易用性,拓展性,高可用性表现不俗。
#### 概念
一般的消息队列,会有三个概念,发送者,接收者,队列。RabbitMQ 在这个基本的概念上添加了一层,在发消息者 和 队列中,叫交换器,exchange ,这样就变成,发消息者把消息给交换器,交换器再经过策略把消息传给队列。

其中比较重要的概念有,虚拟主机,交换器,队列 ,绑定
* 虚拟主机:一个虚拟主机持有一组交换机,队列和绑定。用户只能在虚拟主机的颗粒进行权限控制,若是想禁止A组访问B组的交换机/队列和绑定,必须为A和B分别建立一个虚拟主机,每个RabbitMQ服务器都有一个默认的虚拟主机。
* 交换机 exchenge 用于转发消息,可是不会存储,所以须要Queue bind 。否则那exchange会直接丢弃producer发送过来的消息,这里一个重要概念,路由键,消息到交换器,交换器会转发到对应的队列中,这个须要路由键控制。
* 绑定 交换机须要和队列相绑定,多对多关系。

#### 交换机 Exchange
交换机的功能主要是接收消息并转发到绑定的队列中,交换机不存消息,在启用ack模式后,交换机找不到队列会返回错误。交换机有4终类型,direct ,topic,headers and fanout @ direct: direct 启动先匹配,再投送。即再绑定的时候设置一个值,routing_key 消息的routing_key 匹配时,才会投送到绑定的队列中。 @ Topic : 按规则转发消息 @ Headers : 设置 header attribute 参数类型的交换机。 @ fanout: 转发消息到全部的绑定队列 * direct exchange direct exchange 是RabbitMQ 默认的就交换机模式,最简单的,根据key 找队列。一个队列上能够绑定多个key。 * Topic Exchange Topic Exchange 转发消息主要是通配符,队列和交换机绑定会定义一种路由模式,路由键匹配上路由模式后才能经过交换机转发消息。 这种交换机模式下: ** 路由键 必须是一串字符串,用英文句号隔开,好比,aaa.su ** 路由模式必须包含一个标识符 \*,\#, 主要用于匹配路由键制定位置的单词,好比,aaa.b.*,能匹配的路由键就是 第一个单词aaa,第三个单词b。若是末尾是井号(\#),能够匹配全部以此开头的路由键。 ** 具体的代码,第一参数 交换机, 第二参数 routing key 第三参数为具体消息。 > rabbitTemplate.convertAndSend("testTopicExchange","key1.a.c.key2", " this is RabbitMQ!"); topic 和 direct 相似,匹配上支持了模式,在点分的 routing——key 模式中,通配符两个,型号 表示一个词,井号 表示多个或零个。 * Headers Exchange headers 也是根据规矩匹配,对比direct 和 topic 固定的是用routing key ,headers 是一个自定义匹配规则的类型,在队列和交换机绑定时,会设定一组键值对规则,消息中也包括一组键值对,若是这些键值对,有一对或者所有匹配的时候,消息就会被投放到对应的队列。 * Fanout Exchange fanout exchange 消息广播模式,无论路由键或路由模式,会把消息发给全部绑定到它的队列,若是配置了routing key 会被忽略。 #### springBoot 集成 RabbitMQ ##### 1,添加pom包 spring boot stater amqp 包 ##### 2,配置文件 > 配置Rabbitmq 的安装地址,端口,以及帐户信息。 spring.application.name=spirng-boot-rabbitmq spring.rabbitmq.host=192.168.0.86

spring.rabbitmq.port=5672 spring.rabbitmq.username=admin spring.rabbitmq.password=123456

3 队列配置

public Queue queue(){ return new Queue(“hello”)}

发送 rabbitTemplate 是springBoot 提供的默认实现 public class helloSender{ @autowired private amqpTemplate rabbitTemplate;

public void send(){ string context = "hello" + new Date(); System.out.pringln("Sender:"+context); this.rabbitTemplate.convertAndSend("hello",context); }

}

--接收者 @Component @RabbitListener public class HelloReceiver { @RabbitHandler public void process(String hello){ System.out.println("Receiver :"+hello); } } --测试 @RunWith(SpringRunner.class) @SpringBootTest public class RabbitMqHelloTest{

@Autowired private HelloSender helloSender; @Test public void hello() throws Exception{ hrlloSender.send(); }

} -- 接收者和发送者必须一致 --发送者 public void send(User user){ system.out.println("Sender object: "+user.toString()); this.rabbitTemplate.convertAndSend("object",user); }

--接收者 @RabbitHandler public void process(User user){ system.out.println("Receiver object :" +user); } --Topic Exhange 能够根据不一样的routing key 自由绑定不一样的队列,须要对topic 规则配置。 @Configuration public class RopicRabbitConfig { final static String message = "topic.message"; final static String messages = "topic.messages";

@Bean public Queue queueMessage(){ return new Queue(TopicRabbitConfig.message); } @Bean public Queue queueMessages(){ return new Queue(TopicRabbitConfig.messages); } @Bean TopicExchange exchange(){ return new TopicExchange("exchange"); } @Bean Binding bindingExchangeMessage(Queue queueMessage,TopicExchange exchange){ return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message"); } @Bean Binding bindingExchangeMessages (Queue queueMessages,TopicExchange exchange){ return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#"); }

}

使用queueMessages 同时匹配两个队列,queueMessage只匹配“topic.message” public void send1(){ String context = "hi ,i am message1"; System.out.println("Sender: "+context); this.rabbitTemplate.convertAndSend("exchange","topic.message",context); }

public void send2(){ String context = "hi i am message2"; System.out.println("Sender :"+context); this.rabbitTemplate.convertAndSend("exchange","topic.message",context);

} --Fanout Exchange Fanout 是咱们熟悉的广播模式或者订阅模式。给Fanout交换机发送消息,绑定了这个交换机的全部队列都收到这个消息。 Fanout @Configuration public class FaoutRabbitConfig{ @Bean public Queue AMessage(){ return new Queue("fanout.A"); }

@Bean public Queue BMessage(){ return new Queue("fanout.B"); } @Bean public Queue CMessage(){ return new Queue("fanout.C"); } @Bean FanoutExchange fanoutExchange(){ return new FanoutExchange("fanoutExchange"); } @Bean Binding bindingExchangeA(Queue AMessage,FanoutExchange fanoutExchange){ return BindingBuilder.bind(Amessage).to(fanoutExchange); } @Bean Binding bindingExchangeB(Queue BMessage,FanoutExchange fanoutExchange){ return BindingBuilder.bind(Bmessage).to(fanoutExchange); } @Bean Binding bindingExchangeC(Queue CMessage,FanoutExchange fanoutExchange){ return BindingBuilder.bind(CMessage).to(fanoutExchange); }

}

spring boot 定时任务

pom 包引入

spring boot starter 包

启动定时注解

启动类上加@EnableScheduling 开启定时 @SpringBootApplication @EnableScheduling public class Application{

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

}

####建立定时任务实现类 @Component public class SchedulerTask{ private int count = 0;

@Scheduled(cron="*/6 * * * *?")--@Scheduled(fixedTate = 6000) private void pricess(){ System.out.println("this is scheduler task runing "+(count++)); }

}

相关文章
相关标签/搜索