Spring Boot學(xué)習(xí)筆記一:快速入門集成JPA mybatis rabbitmq mongodb redis

image.png
  • 交流或更多內(nèi)容請(qǐng)關(guān)注我的公眾號(hào):nezha_blog
  • 我的技術(shù)博客:https://nezha.github.io
微信公眾號(hào)

1. Spring Boot學(xué)習(xí)筆記--全注解方式

Spring Boot教程與Spring Cloud教程

2. pring boot中文幫助文檔

Spring Boot Reference Guide中文翻譯 -《Spring Boot參考指南》---說(shuō)明:本文檔翻譯的版本:1.4.1.RELEASE劣坊。

3. 常用注解

  • @RestController
    返回json形式的結(jié)果箫锤,便于前后端分離蛹磺。是@ResponseBody 和 @Controller的組合體
  • @RequestMapping
    配置url映射
  • @EnableAutoConfiguration
  • @Configuration
  • @ComponentScan
  • @SpringBootApplication

很多Spring Boot開(kāi)發(fā)者總是使用 @Configuration 谁榜, @EnableAutoConfiguration@ComponentScan 注解他們的main類悯舟。由于這些注解被如此頻繁地一塊使用(特別是你遵循以上最佳實(shí)踐時(shí)),Spring Boot提供一個(gè)方便的 @SpringBootApplication 選擇。

@SpringBootApplication 注解等價(jià)于以默認(rèn)屬性使用 @Configuration@EnableAutoConfiguration@ComponentScan 诫惭。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  • @ConfigurationProperties

屬性注入,prefix指代注入的配置來(lái)自connection的對(duì)象

@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
    private String username;
    private InetAddress remoteAddress;
    // ... getters and setters
}
connection:
  name: 趙武
  age: 18
  job: Java研發(fā)工程師

為了使用@ConfigurationProperties beans翁锡,你可以使用與其他任何bean相同的方式注入它們

@Service
public class MyService {
    @Autowired
    private ConnectionSettings connection;
    //...
    @PostConstruct
    public void openConnection() {
        Server server = new Server();
        this.connection.configure(server);
    }
}
  • @EnableConfigurationProperties
  • @Component@Bean
    @Bean主要被用在方法上蔓挖,來(lái)顯式聲明要用生成的類
  • @Profiles

Spring Profiles提供了一種隔離應(yīng)用程序配置的方式,并讓這些配置只能在特定的環(huán)境下生效馆衔。

spring:
  profiles:
    active: dev
  • @Value

用于獲取配置文件下的配置項(xiàng)

people:
  name: 趙武
  age: 18
  job: Java研發(fā)工程師
    @Value("${people.name}")
    private String name;
  • @Controller

@PathVariable,@RequestParam
@GetMapping,@PostMapping:Get 或Post方式的請(qǐng)求瘟判,組合模式

@PathVariable的使用,獲取請(qǐng)求參數(shù)

@RequestMapping(value="/hello/{id}",method = RequestMethod.GET)
public String sayhello(@PathVariable("id")Integer myid){
    return "id:"+myid;
}

@RequestParam的使用角溃,獲取傳統(tǒng)方式的參數(shù)

@RequestMapping(value="/hi",method = RequestMethod.GET)
public String sayhi(@RequestParam(value = "id",required = false,defaultValue = "100")Integer myid){
    return "id:"+myid;
}

4. spring data JPA -- 單數(shù)據(jù)源

具體的實(shí)現(xiàn)代碼demo:Spring-Boot-Restful-JPA的demo程序

定義了對(duì)象持久化的標(biāo)準(zhǔn)拷获,主要是對(duì)Hibernate的整合

現(xiàn)階段發(fā)現(xiàn)和mybatis的直觀操作很一致,都是可能集中管理數(shù)據(jù)庫(kù)連接與釋放减细,JPA想比較于mybatis可以自動(dòng)建表匆瓜,不知道算不算一種優(yōu)勢(shì),在我看來(lái)不算是未蝌。畢竟表結(jié)構(gòu)基本上數(shù)據(jù)庫(kù)工程師都搞定了的事驮吱。

1.加入依賴

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

2.配置數(shù)據(jù)庫(kù)和JPA

ddl-auto:創(chuàng)建的方式

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/coder
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true

3.創(chuàng)建Mapper對(duì)象

@Entity: 持久化實(shí)例

@Table: 自定義表的名稱

@Entity
//@Table(name = "programmer")
public class Coder {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;
    private Integer age;
    public Coder(){
        
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

4.集成JpaRepository

主要是基于Hibernate的

public interface CoderRepository extends JpaRepository<Coder,Integer> {
    //這個(gè)是擴(kuò)展開(kāi)來(lái)的查詢方式
    public List<Coder> findByAge(Integer age);
}

5.實(shí)現(xiàn)一個(gè)CoderController,實(shí)現(xiàn)增刪改查萧吠。

@RestController
public class CoderController {
    @Autowired
    private CoderRepository coderRepository;

    //1.Get方式請(qǐng)求左冬,查詢所有程序員信息
    @GetMapping(value = "/coders")
    public List<Coder> coderList(){
        return coderRepository.findAll();
    }
    //2.Post方式,增加程序員
    @PostMapping(value = "/coders")
    public Coder CoderAdd(@RequestParam("name")String name,@RequestParam("age")Integer age){
        Coder coder = new Coder();
        coder.setAge(age);
        coder.setName(name);
        return  coderRepository.save(coder);
    }
    //3.通過(guò)id查詢一個(gè)人
    @GetMapping(value = "/coders/{id}")
    public Coder CoderFindOne(@PathVariable("id")Integer id){
        return coderRepository.findOne(id);
    }
    //4.通過(guò)id刪除一個(gè)人
    @DeleteMapping(value = "/coders/{id}")
    public void CoderDelete(@PathVariable("id")Integer id){
        coderRepository.delete(id);
    }
    //5.更新一個(gè)人,用Postman模擬的時(shí)候注意:用x-www-form-urlencoded
    @PutMapping(value = "/coders/{id}")
    public Coder CoderUpdateOne(@PathVariable("id")Integer id, @RequestParam("name") String name, @RequestParam("age")Integer age){
        Coder coder = new Coder();
        coder.setId(id);
        coder.setName(name);
        coder.setAge(age);
        return coderRepository.save(coder);
    }
    //6.擴(kuò)展Jpa接口纸型,按照年齡查找
    @GetMapping(value = "/coder/age/{age}")
    public List<Coder> CoderFindAll(@PathVariable("age")Integer age){
        return coderRepository.findByAge(age);
    }

}

6.實(shí)現(xiàn)mysql的事務(wù)

  • 首先新建一個(gè)Service類:CoderService
@Service
public class CoderService {
    @Autowired
    CoderRepository coderRepository;

    @Transactional
    public void insertTwo(){
        Coder coderA = new Coder();
        coderA.setAge(101);
        coderA.setName("1");
        coderRepository.save(coderA);

        Coder coderB = new Coder();
        coderB.setAge(102);
        coderB.setName("102");
        coderRepository.save(coderB);

    }
}
  • 在CoderController中自動(dòng)載入coderService
@Autowired
private CoderService coderService;
  • 在CoderController調(diào)用service拇砰。
//7.使用事務(wù)梅忌,同時(shí)插入兩個(gè)人的數(shù)據(jù)
@PostMapping(value = "coder/two")
public void coderTwo(){
    coderService.insertTwo();
}

7.使用@Query實(shí)現(xiàn)自定義sql查詢

  • CoderRepository實(shí)現(xiàn)下面代碼
@Query("select p from Coder p where p.id = (select max(p2.id) from Coder p2)")
    Coder getMaxIdCoder();
  • CoderController中使用getMaxIdCoder方法
//8.自定義sql語(yǔ)句查詢
@GetMapping(value = "/coder/find")
public Coder CoderFindByTask(){
    return coderRepository.getMaxIdCoder();
}

5. Spring Boot MyBatis -- 單數(shù)據(jù)源

基于注解方式的Mybatis其實(shí)和JPA很類似,不過(guò)mybatis不提供自動(dòng)創(chuàng)建表的操作除破。這點(diǎn)上jpa更好些牧氮。

我的demo程序,在我的github上:spring-boot-mybatis-mysql

引用博客:
Spring Boot + MyBatis + MySQL 整合--簡(jiǎn)書 FlySheep_ly

程序員DD:Spring Boot整合MyBatis

     [Spring Boot中使用MyBatis注解配置詳解](http://blog.didispace.com/mybatisinfo/)

1.引入依賴

<!-- 添加 MyBatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.2.0</version>
</dependency>
<!-- 添加 MySQL -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.41</version>
</dependency>

2.application.properties中配置mysql的連接配置

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

3.創(chuàng)建映射對(duì)象User

關(guān)于序列化的實(shí)現(xiàn)皂岔,最好還是實(shí)現(xiàn)一下蹋笼。

import java.io.Serializable;

public class User implements Serializable{
    private static final long serialVersionUID = -5554561712056198940L;

    private Long id;
    private String name;
    private Integer age;

    public User(){
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

}

4.創(chuàng)建User映射的操作UserMapper

關(guān)于Mapper的更多操作,請(qǐng)參考mybatis官網(wǎng)

/**
 * Created by nezha on 2017/4/26.
 */

@Mapper
public interface UserMapper {
    /**
     * 添加操作躁垛,返回新增元素的 ID
     * @param User
     */
    @Insert("insert into person(name,age) values(#{name},#{age})")
    @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
    void insert(User user);
    /**
     * 查詢所有
     * @return
     */
    @Select("select id,name,age from person")
    List<User> selectAll();

    @Select("SELECT * FROM USER WHERE NAME = #{name}")
    User findByName(@Param("name") String name);
}

5.調(diào)用測(cè)試

發(fā)現(xiàn)Restful風(fēng)格真是好習(xí)慣剖毯,很好用很實(shí)用。

@EnableTransactionManagement
@RestController
public class TestController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping(value = "/test/{name}")
    public User findOne(@PathVariable("name")String name){
        return userMapper.findByName(name);
    }
}

可能出現(xiàn)的問(wèn)題:

mybatis+spring boot, mapper 提示Could not autowire. 一直提示不能加載

image.png
  • 解決方案

修改idea配置教馆,將spring 的severity的值設(shè)置為"warning", 如下:

image.png

如果想進(jìn)一步縮小修改范圍的話:

Alt + Enter quick fix or change settings
Settings - Editor - Inspections - Spring - Spring Core - Code - Autowiring for Bean Class - warning

關(guān)于多源配置的問(wèn)題:

1.Spring Boot 整合 Mybatis 實(shí)現(xiàn) Druid 多數(shù)據(jù)源詳解

2.springboot+mybatis多數(shù)據(jù)源最簡(jiǎn)解決方案

6. Spring Boot RabbitMQ

我的demo程序:spring-boot-RabbitMQ

Spring Boot RabbitMQ 入門--這篇文章寫得不錯(cuò),關(guān)于RabbitMQ的三種Exchange方式講的很好逊谋。不過(guò)代碼不是很簡(jiǎn)潔。

RabbitMQ詳解--純潔的微笑的文章代碼很簡(jiǎn)潔

安裝與配置

翟永超-Spring boot系列教程

RabbitMQ的三種Exchange方式

1.Direct Exchange

image.png

如果 routing key 匹配, 那么Message就會(huì)被傳遞到相應(yīng)的queue中土铺。其實(shí)在queue創(chuàng)建時(shí)胶滋,它會(huì)自動(dòng)的以queue的名字作為routing key來(lái)綁定那個(gè)exchange。

2.Fanout Exchange

image.png

只需要簡(jiǎn)單的將隊(duì)列綁定到交換機(jī)上悲敷。一個(gè)發(fā)送到交換機(jī)的消息都會(huì)被轉(zhuǎn)發(fā)到與該交換機(jī)綁定的所有隊(duì)列上究恤。很像子網(wǎng)廣播,每臺(tái)子網(wǎng)內(nèi)的主機(jī)都獲得了一份復(fù)制的消息后德。Fanout交換機(jī)轉(zhuǎn)發(fā)消息是最快的部宿。

3.Topic Exchange

image.png

將路由鍵和某模式進(jìn)行匹配。此時(shí)隊(duì)列需要綁定要一個(gè)模式上瓢湃。符號(hào)“#”匹配一個(gè)或多個(gè)詞理张,符號(hào)“”匹配不多不少一個(gè)詞。因此“audit.#”能夠匹配到“audit.irs.corporate”绵患,但是“audit.

實(shí)例講解

三種方式最主要的文件就三個(gè):

1.sender的配置

2.receiver的配置

3.rabbitConfig的配置

下面雾叭,我們通過(guò)在Spring Boot應(yīng)用中整合RabbitMQ,并實(shí)現(xiàn)一個(gè)簡(jiǎn)單的發(fā)送落蝙、接收消息的例子來(lái)對(duì)RabbitMQ有一個(gè)直觀的感受和理解织狐。

在Spring Boot中整合RabbitMQ是一件非常容易的事,因?yàn)橹拔覀円呀?jīng)介紹過(guò)Starter POMs筏勒,其中的AMQP模塊就可以很好的支持RabbitMQ移迫,下面我們就來(lái)詳細(xì)說(shuō)說(shuō)整合過(guò)程:

1.pom依賴引入

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

2.連接配置

spring.application.name=rabbitmq-hello
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

3.創(chuàng)建消息生產(chǎn)者Sender

創(chuàng)建消息生產(chǎn)者Sender。通過(guò)注入AmqpTemplate接口的實(shí)例來(lái)實(shí)現(xiàn)消息的發(fā)送奏寨,AmqpTemplate接口定義了一套針對(duì)AMQP協(xié)議的基礎(chǔ)操作起意。在Spring Boot中會(huì)根據(jù)配置來(lái)注入其具體實(shí)現(xiàn)。在該生產(chǎn)者病瞳,我們會(huì)產(chǎn)生一個(gè)字符串揽咕,并發(fā)送到名為hello的隊(duì)列中悲酷。

@Component
public class Sender {
    @Autowired
    AmqpTemplate amqpTemplate;
    public void send() {
        String context = "hello " + new Date();
        System.out.println("Sender : " + context);
        this.amqpTemplate.convertAndSend("hello", context);
    }
}

4.創(chuàng)建消息消費(fèi)者Receiver

創(chuàng)建消息消費(fèi)者Receiver。通過(guò)@RabbitListener注解定義該類對(duì)hello隊(duì)列的監(jiān)聽(tīng)亲善,并用@RabbitHandler注解來(lái)指定對(duì)消息的處理方法设易。所以,該消費(fèi)者實(shí)現(xiàn)了對(duì)hello隊(duì)列的消費(fèi)蛹头,消費(fèi)操作為輸出消息的字符串內(nèi)容顿肺。

@Component
@RabbitListener(queues = "hello")
public class Receiver {
    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver1 : " + hello);
    }
}

5.創(chuàng)建RabbitMQ的配置類RabbitConfig

創(chuàng)建RabbitMQ的配置類RabbitConfig,用來(lái)配置隊(duì)列渣蜗、交換器屠尊、路由等高級(jí)信息。這里我們以入門為主耕拷,先以最小化的配置來(lái)定義讼昆,以完成一個(gè)基本的生產(chǎn)和消費(fèi)過(guò)程。

@Configuration
public class RabbitConfig {


    //1.配置一個(gè)名為hello的一對(duì)一的消息隊(duì)列
    @Bean
    public Queue helloQueue() {
        return new Queue("hello");
    }
}

5.單元測(cè)試:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = HelloApplication.class)
public class HelloApplicationTests {
    @Autowired
    private Sender sender;
    @Test
    public void hello() throws Exception {
        sender.send();
    }
}

7. Spring Boot mongodb

spring boot mongodb 的demo程序:spring-boot-mongodb

安裝與配置

1骚烧、進(jìn)入mongodb的shell : mongo

2浸赫、切換數(shù)據(jù)庫(kù): use admin

3、添加用戶赃绊,指定用戶的角色和數(shù)據(jù)庫(kù):

db.createUser(  
  { user: "admin",  
    customData:{description:"superuser"},
    pwd: "admin",  
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]  
  }  
)  
user字段既峡,為新用戶的名字;
pwd字段碧查,用戶的密碼运敢;
cusomData字段,為任意內(nèi)容么夫,例如可以為用戶全名介紹者冤;
roles字段肤视,指定用戶的角色档痪,可以用一個(gè)空數(shù)組給新用戶設(shè)定空角色。在roles字段,可以指定內(nèi)置角色和用戶定義的角色邢滑。

4腐螟、查看創(chuàng)建的用戶 : show users 或 db.system.users.find()

5、啟用用戶權(quán)限:

修改配置文件困后,增加配置:

$ vim /etc/mongod.conf
security:
  authorization: enabled

6.重新啟動(dòng)mongodb

sudo service mongod restart

7.使用用戶管理賬戶登錄認(rèn)證

use admin
db.auth('admin', 'admin')

8.遠(yuǎn)程登陸

mongo 123.xxx.xxx.xxx:27017/amdin -uadmin -padmin

第一個(gè)admin:指代數(shù)據(jù)庫(kù)
第二個(gè)admin:指代用戶名
第三個(gè)admin:指代密碼

spring boot 集成 mongodb

1.引入依賴

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

2.創(chuàng)建存儲(chǔ)的實(shí)體

創(chuàng)建要存儲(chǔ)的User實(shí)體乐纸,包含屬性:id、username摇予、age

public class User {

    @Id
    private String id;

    private String username;
    private Integer age;

    public User(String username, Integer age) {
//        this.id = id;
        this.username = username;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "username:"+username+"--age:"+age;
    }
}

3.實(shí)現(xiàn)User的數(shù)據(jù)訪問(wèn)對(duì)象

實(shí)現(xiàn)User的數(shù)據(jù)訪問(wèn)對(duì)象:UserRepository

public interface UserRepository extends MongoRepository<User, String> {

    User findByUsername(String username);

}

4.配置mongodb的連接

#mongodb3.X的配置
spring.data.mongodb.uri=mongodb://admin:admin@123.206.xxx.xxx:27017/test
#mongodb2.x的配置
spring.data.mongodb.host=localhost spring.data.mongodb.port=27017

5.在單元測(cè)試中調(diào)用

@RunWith(SpringRunner.class)
@SpringBootTest
public class Test05ApplicationTests{
    @Autowired
    private UserRepository userRepository;

    @Test
    public void test() {
        userRepository.deleteAll();
        // 創(chuàng)建三個(gè)User汽绢,并驗(yàn)證User總數(shù)
        userRepository.save(new User("didi", 30));
        userRepository.save(new User("mama", 40));
        userRepository.save(new User("kaka", 50));
        Assert.assertEquals(3, userRepository.findAll().size());

        // 刪除一個(gè)User,再驗(yàn)證User總數(shù)
        User u = userRepository.findByUsername("didi");
        System.out.println(u.toString());
        userRepository.delete(u);
        Assert.assertEquals(2, userRepository.findAll().size());
    }

}

出現(xiàn)的問(wèn)題

1.發(fā)現(xiàn)運(yùn)行成功侧戴,但是查不到數(shù)據(jù)

主要是自己理解錯(cuò)誤宁昭,mongodb數(shù)據(jù)庫(kù)下還有collection(相當(dāng)于表).然后針對(duì)每一個(gè)Database下可能有多個(gè)collection

8. Spring Boot redis

redis的demo程序:nezha/spring-boot-redis

1.引入依賴

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

2.參數(shù)配置

# REDIS (RedisProperties)
# Redis數(shù)據(jù)庫(kù)索引(默認(rèn)為0)
spring.redis.database=0
# Redis服務(wù)器地址
spring.redis.host=123.206.xxx.xxx
# Redis服務(wù)器連接端口
spring.redis.port=6379
# Redis服務(wù)器連接密碼(默認(rèn)為空)
spring.redis.password=
# 連接池最大連接數(shù)(使用負(fù)值表示沒(méi)有限制)
spring.redis.pool.max-active=-1
# 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒(méi)有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=16
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=0
# 連接超時(shí)時(shí)間(毫秒)
spring.redis.timeout=0

3.測(cè)試訪問(wèn)

@RunWith(SpringRunner.class)
@SpringBootTest
public class Test04ApplicationTests {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Test
    public void test() throws Exception {
        // 保存字符串
        stringRedisTemplate.opsForValue().set("aaa", "111");
        Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
    }

}

9. Spring Boot定時(shí)任務(wù)

定時(shí)任務(wù)demo程序:spring-boot-schedule

1.pom包配置

這部分基本的spring boot啟動(dòng)項(xiàng)就行跌宛,沒(méi)有什么特別的依賴包

2.啟動(dòng)類啟用定時(shí)

@EnableScheduling
@SpringBootApplication
public class ScheduleApplication {

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

3.創(chuàng)建定時(shí)任務(wù)實(shí)現(xiàn)類

定時(shí)任務(wù)一

/**
 * Created by nezha on 2017/4/28.
 */
@Component
public class SchedulerTask {
    private int count = 0;

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

定時(shí)任務(wù)二

/**
 * Created by nezha on 2017/4/28.
 */
@Component
public class SchedulerTask2 {
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 6000)
    public void reportCurrentTime() {
        System.out.println("現(xiàn)在時(shí)間:" + dateFormat.format(new Date()));
    }
}

4.參數(shù)說(shuō)明

@Scheduled 參數(shù)可以接受兩種定時(shí)的設(shè)置,一種是我們常用的cron="*/6 * * * * ?",一種是 fixedRate = 6000积仗,兩種都表示每隔六秒打印一下內(nèi)容疆拘。

fixedRate 說(shuō)明

  • @Scheduled(fixedRate = 6000) :上一次開(kāi)始執(zhí)行時(shí)間點(diǎn)之后6秒再執(zhí)行
  • @Scheduled(fixedDelay = 6000) :上一次執(zhí)行完畢時(shí)間點(diǎn)之后6秒再執(zhí)行
  • @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延遲1秒后執(zhí)行,之后按fixedRate的規(guī)則每6秒執(zhí)行一次

10. Spring Boot相關(guān)技術(shù)

自定義圖標(biāo)

Spring Boot自定義Banner---自定義圖標(biāo)

部署spring項(xiàng)目

1.IntelliJ Idea中直接運(yùn)行

2.mvn spring-boot:run

3.mvn install >>> 會(huì)生成jar文件寂曹,執(zhí)行jar文件哎迄。

spring boot測(cè)試的時(shí)候,怎么單元測(cè)試

1.使用@SpringBootTest
文件主要實(shí)在test目錄下

@RunWith(SpringRunner.class)
@SpringBootTest
public class Test05ApplicationTests{
    @Autowired
    private UserRepository userRepository;

    @Test
    public void test() {
        userRepository.deleteAll();
        // 創(chuàng)建三個(gè)User隆圆,并驗(yàn)證User總數(shù)
        userRepository.save(new User("didi", 30));
        userRepository.save(new User("mama", 40));
        userRepository.save(new User("kaka", 50));
    }
}

2.使用@SpringBootApplication

在主目錄下com.nezha/

@SpringBootApplication
public class Application implements CommandLineRunner {
    @Autowired
    private CustomerRepository repository;
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @Override
    public void run(String... args) throws Exception {
        repository.deleteAll();
        // save a couple of customers
        repository.save(new Customer("Alice", "Smith"));
        repository.save(new Customer("Bob", "Smith"));
    }
}

3.使用RestController

這種方式很方便漱挚,很好用,有些時(shí)候我會(huì)用渺氧。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末棱烂,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子阶女,更是在濱河造成了極大的恐慌颊糜,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,858評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件秃踩,死亡現(xiàn)場(chǎng)離奇詭異衬鱼,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)憔杨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門鸟赫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人消别,你說(shuō)我怎么就攤上這事抛蚤。” “怎么了寻狂?”我有些...
    開(kāi)封第一講書人閱讀 165,282評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵岁经,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我蛇券,道長(zhǎng)缀壤,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,842評(píng)論 1 295
  • 正文 為了忘掉前任纠亚,我火速辦了婚禮塘慕,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蒂胞。我一直安慰自己图呢,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著蛤织,像睡著了一般拥娄。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上瞳筏,一...
    開(kāi)封第一講書人閱讀 51,679評(píng)論 1 305
  • 那天稚瘾,我揣著相機(jī)與錄音,去河邊找鬼姚炕。 笑死摊欠,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的柱宦。 我是一名探鬼主播些椒,決...
    沈念sama閱讀 40,406評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼掸刊!你這毒婦竟也來(lái)了免糕?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 39,311評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤忧侧,失蹤者是張志新(化名)和其女友劉穎石窑,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體蚓炬,經(jīng)...
    沈念sama閱讀 45,767評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡松逊,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了肯夏。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片经宏。...
    茶點(diǎn)故事閱讀 40,090評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖驯击,靈堂內(nèi)的尸體忽然破棺而出烁兰,到底是詐尸還是另有隱情,我是刑警寧澤徊都,帶...
    沈念sama閱讀 35,785評(píng)論 5 346
  • 正文 年R本政府宣布沪斟,位于F島的核電站,受9級(jí)特大地震影響碟贾,放射性物質(zhì)發(fā)生泄漏币喧。R本人自食惡果不足惜轨域,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評(píng)論 3 331
  • 文/蒙蒙 一袱耽、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧干发,春花似錦朱巨、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,988評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)琼讽。三九已至,卻和暖如春洪唐,著一層夾襖步出監(jiān)牢的瞬間钻蹬,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,101評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工凭需, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留问欠,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,298評(píng)論 3 372
  • 正文 我出身青樓粒蜈,卻偏偏與公主長(zhǎng)得像顺献,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子枯怖,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,822評(píng)論 6 342
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理注整,服務(wù)發(fā)現(xiàn),斷路器度硝,智...
    卡卡羅2017閱讀 134,659評(píng)論 18 139
  • 這些屬性是否生效取決于對(duì)應(yīng)的組件是否聲明為 Spring 應(yīng)用程序上下文里的 Bean(基本是自動(dòng)配置的)肿轨,為一個(gè)...
    發(fā)光的魚(yú)閱讀 1,426評(píng)論 0 14
  • 近日,網(wǎng)絡(luò)安全和信息化領(lǐng)導(dǎo)小組發(fā)布的安全信息通報(bào)曝光了惠普電腦存在的隱藏鍵盤記錄器的安全問(wèn)題蕊程,雖然惠普方面表示此事...
    智未來(lái)閱讀 279評(píng)論 0 0
  • 文/畫 在此與自己相遇 《夢(mèng)-破風(fēng)》 推開(kāi)門 鞋子從腳上滑落 身體變的很輕 裙擺飛揚(yáng) 我飛了起來(lái) 飛出那扇窗 風(fēng)把...
    雪鯨呀閱讀 525評(píng)論 1 9