spring boot如何在最短時間里快速搭建微服務框架,詳細教程貢上(spring boot

      網友投稿 974 2025-03-31

      前言:

      Spring Boot是為了簡化Spring應用的創建、運行、調試、部署等而出現的,使用它可以做到專注于Spring應用的開發,而無需過多關注XML的配置。

      簡單來說,它提供了一堆依賴打包,并已經按照使用習慣解決了依賴問題—習慣大于約定。

      Spring Boot默認使用tomcat作為服務器,使用logback提供日志記錄。

      Spring Boot的主要優點:

      1.為所有Spring開發者更快的入門

      2.開箱即用,提供各種默認配置來簡化項目配置

      3.內嵌式容器簡化Web項目

      4.沒有冗余代碼生成和XML配置的要求

      技術棧:

      1.Java 8

      2.Maven

      3.Spring-boot

      4.Mybatis

      5.Redis

      6.Lombok

      7.Swagger2

      8.Jenkins

      9.SonarQuber

      一、使用Maven構建項目

      1、通過 SPRING INITIALIZR 工具生產基礎項目

      通過訪問:http://start.spring.io/ 快速創建Spring-boot 的服務框架。

      初始化相應信息后,下載壓縮包。解壓完成后,用IDEA打開項目,項目的目錄結構:

      總體流程:

      訪問:http://start.spring.io/

      選擇構建工具Maven Project、Spring Boot版本1.3.2以及一些工程基本信息

      點擊Generate Project下載項目壓縮包

      解壓項目包,并用IDE以Maven項目導入,以IntelliJ IDEA 14為例:

      菜單中選擇File–>New–>Project from Existing Sources…

      選擇解壓后的項目文件夾,點擊OK

      點擊Import project from external model并選擇Maven,點擊Next到底為止。

      若你的環境有多個版本的JDK,注意到選擇Java SDK的時候請選擇Java 7以上的版本

      2、導入Spring-boot 相關依賴

      項目初始化時,相關依賴如下:

      1.spring-boot-starters:核心模塊,包括自動配置支持、日志和YAML

      2.spring-boot-starter-test:測試模塊,包括JUnit、Hamcrest、Mockito

      3.spring-boot-devtools:用于設置熱部署

      org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-devtools true

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      這里我們需要引入Web模塊,需要添加:

      org.springframework.boot spring-boot-starter-web

      1

      2

      3

      4

      3、啟動項目

      添加首頁控制層:

      public String index() { return "hello world!"; } }

      1

      2

      3

      運行DemoApplication中的main方法,啟動服務:

      服務啟動后, 訪問

      http://localhost:8080/index ,可以看到頁面輸出Hello world!。

      二、整合Mybatis

      1、項目依賴

      1.引入連接mysql的必要依賴mysql-connector-java

      2.引入整合MyBatis的核心依賴

      mybatis-spring-boot-starter

      3.引入tk.mybatis 依賴,實現對實體類的增刪改查的代碼

      4.引入pagerhelper 依賴,實現分頁功能

      org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.0 mysql mysql-connector-java 5.1.43 tk.mybatis mapper-spring-boot-starter 1.1.3 com.github.pagehelper pagehelper-spring-boot-starter 1.1.2

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      16

      17

      18

      19

      20

      21

      2、項目配置

      修改resources 下的application.properties文件:

      spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver#實體類掃描包mybatis.type-aliases-package=com.jaycekon.demo.model#Mapper.xml文件掃描目錄mybatis.mapper-locations=classpath:mapper/*.xml#駝峰命名mybatis.configuration.mapUnderscoreToCamelCase=true#tkmapper 工具類mapper.mappers=com.Jaycekon.demo.util.MyMapper mapper.not-empty=falsemapper.identity=MYSQL pagehelper.helperDialect=mysql pagehelper.reas`onable=truepagehelper.supportMethodsArguments=truepagehelper.params=count=countSql

      1

      2

      3

      4

      5

      6

      3、單元測試

      創建實體類,我們引入Lombok相關依賴,用于避免數據Get Set方法的重復創建:

      org.projectlombok lombok 1.16.18 provided

      1

      2

      3

      4

      5

      6

      實體類最終的代碼如下:

      @Data@NoArgsConstructor@AllArgsConstructor@Accessors(chain = true)public class User { private int id; private String username; private String idCard; private String phone; private String password; }

      1

      2

      可以看出,在添加了Lombok之后,我們的Java實體類代碼簡潔了很多。

      接下來,我們需要創建UserMapper數據庫處理類。由于MyMapper已經幫我們實現了基本的CRUD操作,因此我們這里并不需要再重寫操作,我可以先一個根據用戶名查找的方法:

      @Mapperpublic interface UserMapper extends MyMapper { @Select("select * from user where username=#{username}") User selectByName(String username); }

      1

      2

      MyMapper 類位于util目錄下:

      public interface MyMapper extends Mapper, MySqlMapper { }

      1

      2

      這里需要注意,MyMapper 與我們的實體類Mapper 不能放在同一個目錄。

      測試類:

      @RunWith(SpringRunner.class)@SpringBootTest@MapperScan("com.Jaycekon.demo.mapper")public class UserMapperTest { @Autowired private UserMapper mapper; @Test public void testInset() { User user = new User(1, "Jaycekon","1234","1234","123"); int i = mapper.insert(user); Assert.assertNotEquals(0, i); } @Test public void testSelect(){ User user = mapper.selectByName("Jaycekon"); Assert.assertNotEquals(null,user); } }

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      三、整合Redis

      1、相關依賴

      Spring Boot提供的數據訪問框架Spring Data Redis基于Jedis。可以通過引入 spring-boot-starter-redis 來配置依賴關系。

      org.springframework.boot spring-boot-starter-redis

      1

      2

      3

      2、Redis 配置

      1、Spring-boot連接單機版Redis的配置如下:

      Spring Boot如何在最短時間里快速搭建微服務框架,詳細教程貢上(spring boot)

      #REDIS (RedisProperties)# Redis數據庫索引(默認為0)spring.redis.database=0# Redis服務器地址spring.redis.host=localhost# 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

      2、Spring-boot連接Sentinel哨兵集群配置:

      #REDIS (RedisProperties)# Redis數據庫索引(默認為0)spring.redis.database=0# Redis服務器地址#spring.redis.host=localhost# 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#哨兵監聽redis server名稱spring.redis.sentinel.master=cn-test-master#哨兵的配置列表spring.redis.sentinel.nodes=localhost:26379,localhost:36379,localhost:46379

      3、Redis 操作工具類

      1、StringRedisTemplate工具類

      StringRedisTemplate 工具類可以解決字符串級別的Redis操作。在寫好配置后,可以直接通過Autowried 就可以注入對象。

      @RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(Application.class)public class ApplicationTests { @Autowired private StringRedisTemplate stringRedisTemplate; @Test public void test() throws Exception { // 保存字符串 stringRedisTemplate.opsForValue().set("aaa", "111"); Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa")); } }

      1

      2

      3

      4

      5

      6

      7

      2、RedisTemplate工具類

      可以處理大部分的序列化操作,在這里我封裝了一個簡化Redis工具類,后續可以繼續優化。

      @Componentpublic class RedisComponent { @Autowired //操作字符串的template,StringRedisTemplate是RedisTemplate的一個子集 private StringRedisTemplate stringRedisTemplate; private Logger logger = LoggerFactory.getLogger(RedisComponent.class); @Autowired // RedisTemplate,可以進行所有的操作 private RedisTemplate redisTemplate; public void set(String key, String value) { ValueOperations ops = this.stringRedisTemplate.opsForValue(); boolean bExistent = this.stringRedisTemplate.hasKey(key); if (bExistent) { logger.info("this key is bExistent!"); } else { ops.set(key, value); } } public String get(String key) { return this.stringRedisTemplate.opsForValue().get(key); } public void del(String key) { this.stringRedisTemplate.delete(key); } public void sentinelSet(String key, Object object) { redisTemplate.opsForValue().set(key, JSON.toJSONString(object)); } public String sentinelGet(String key) { return String.valueOf(redisTemplate.opsForValue().get(key)); } }

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      16

      17

      四、整合Swagger2

      1、添加Swagger2依賴:

      io.springfox springfox-swagger2 2.7.0 io.springfox springfox-swagger-ui 2.7.0

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      2、創建Swagger2配置類:

      在Application.java同級創建一個Swagger2的配置類:

      @Configuration@EnableSwagger2public class Swagger2 { @Bean public Docket webApi() { return new Docket(DocumentationType.SWAGGER_2) .groupName("DemoAPI接口文檔") .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.Jaycekon.demo.controller")) .paths(PathSelectors.any()).build(); } /** swagger2使用說明: @Api:用在類上,說明該類的作用 @ApiOperation:用在方法上,說明方法的作用 @ApiIgnore:使用該注解忽略這個API @ApiImplicitParams:用在方法上包含一組參數說明 @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一個請求參數的各個方面 paramType:參數放在哪個地方 header-->請求參數的獲取:@RequestHeader query-->請求參數的獲取:@RequestParam path(用于restful接口)-->請求參數的獲取:@PathVariable body(不常用) form(不常用) name:參數名 dataType:參數類型 required:參數是否必須傳 value:參數的意思 defaultValue:參數的默認值 @ApiResponses:用于表示一組響應 @ApiResponse:用在@ApiResponses中,一般用于表達一個錯誤的響應信息 code:數字,例如400 message:信息,例如"請求參數沒填好" response:拋出異常的類 @ApiModel:描述一個Model的信息(這種一般用在post創建的時候,使用@RequestBody這樣的場景,請求參數無法使用@ApiImplicitParam注解進行描述的時候) @ApiModelProperty:描述一個model的屬性 */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Demo使用Swagger2構建RESTful APIs") .description("微信打卡服務") .contact(new Contact("Jaycekon", "http://petstore.swagger.io/v2/swagger.json", "jaycekon@163.com")) .version("1.0") .build(); } }

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      16

      17

      18

      19

      20

      21

      22

      23

      24

      25

      26

      27

      28

      29

      30

      31

      3、在需要生成Api的接口添加注解:

      @Api(tags = "測試用例")@RestController@RequestMapping(value="/users") // 通過這里配置使下面的映射都在/users下,可去除public class UserController { @ApiOperation(value="獲取用戶列表", notes="") @RequestMapping(value={""}, method= RequestMethod.GET) public List getUserList() { return new ArrayList<>(); } @ApiOperation(value="創建用戶", notes="根據User對象創建用戶") @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User") @RequestMapping(value="", method=RequestMethod.POST) public String postUser(@RequestBody User user) { return "success"; } @ApiOperation(value="獲取用戶詳細信息", notes="根據url的id來獲取用戶詳細信息") @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long") @RequestMapping(value="/{id}", method=RequestMethod.GET) public User getUser(@PathVariable Long id) { return new User(); } @ApiOperation(value="更新用戶詳細信息", notes="根據url的id來指定更新對象,并根據傳過來的user信息來更新用戶詳細信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long"), @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User") }) @RequestMapping(value="/{id}", method=RequestMethod.PUT) public String putUser(@PathVariable Long id, @RequestBody User user) { return "success"; } @ApiOperation(value="刪除用戶", notes="根據url的id來指定刪除對象") @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long") @RequestMapping(value="/{id}", method=RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { return "success"; } }

      1

      2

      3

      4

      5

      6

      7

      8

      完成上述代碼添加上,啟動Spring Boot程序,訪問:

      http://localhost:8080/swagger-ui.html

      。就能看到前文所展示的RESTful API的頁面。我們可以再點開具體的API請求,以POST類型的/users請求為例,可找到上述代碼中我們配置的Notes信息以及參數user的描述信息,如下圖所示。

      Spring-boot:快速搭建微服務框架

      四、接入Jenkins&SonarQube

      項目框架搭建好后,我們可以通Jenkins 進行項目的自動發版,以及SonarQube 進行代碼質量檢測。在接入錢,我們需要將項目打包成war包,需要進行以下修改:

      1、修改項目打包類型:

      com.Jaycekon demo 0.0.1-SNAPSHOT war

      1

      2

      3

      4

      2、修改Application.java 文件:

      @SpringBootApplicationpublic class DemoApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(DemoApplication.class); } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }

      1

      2

      3

      4

      5

      首先需要在MetaData 中,加入SonarQube 的項目名(新建的命名):

      然后在Post Steps 中選擇添加 Execute SonarQube Scanner:

      在配置好這兩項后,Jenkins 在編譯文件時,就會執行SonarQube 代碼質量檢測。

      最后,我們可以設置項目在編譯完后,執行shell 腳本,進行項目的自動發版:

      項目編譯完后,會找到項目下的playbook,執行里面的腳本,將我們的項目部署到設定的服務器中。

      最后

      對于Java后端的朋友來說應該是最全面最完整的面試備戰資源庫,為了更好地整理每個模塊,我也參考了很多網上的優質博文和項目。

      力求不漏掉每一個知識點,很多朋友靠著這些內容進行復習,拿到了BATJ等大廠的Offer,也已經幫助了很多的Java學習者,希望也能幫助到你~

      領取方式:Java基礎、算法、數據庫、數據結構、緩存、大數據組件、消息隊列、多線程、大數據組件原理、NIO&RPC。

      Java Spring Spring Boot 微服務

      版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。

      版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。

      上一篇:Word 2016怎么創建目錄?
      下一篇:創建數據透視圖
      相關文章
      亚洲成A人片在线观看中文| 亚洲欧美日韩一区二区三区在线| 亚洲中文字幕乱码一区| 亚洲国产精品美女| 91天堂素人精品系列全集亚洲| 亚洲AV成人无码久久精品老人 | 日本亚洲视频在线| 亚洲人精品午夜射精日韩| 亚洲午夜国产精品无码| 亚洲精品成人网站在线观看 | 亚洲AV成人一区二区三区在线看| 亚洲一区二区三区无码国产| 亚洲人成毛片线播放| 亚洲AV成人无码天堂| 亚洲国产日韩在线人成下载| 亚洲中文字幕人成乱码| 亚洲人成综合网站7777香蕉| 亚洲无码一区二区三区| 亚洲AV永久无码精品一福利| 爱情岛亚洲论坛在线观看| 午夜亚洲福利在线老司机| 亚洲日韩在线观看| 亚洲一区二区女搞男| 久久综合日韩亚洲精品色| 久久亚洲精品人成综合网| 亚洲最大免费视频网| 激情综合亚洲色婷婷五月| 亚洲精品天堂在线观看| 亚洲国产精华液2020| 亚洲精品无码成人片在线观看| 亚洲无码在线播放| 亚洲日本在线看片| 亚洲国产成人超福利久久精品| 国产亚洲中文日本不卡二区| 亚洲AV成人无码久久WWW| 亚洲精品无码激情AV| 久久亚洲国产视频| 亚洲电影在线免费观看| 一本色道久久88—综合亚洲精品| 精品国产日韩亚洲一区在线| 国产亚洲成人久久|