springboot 微服務框架---分佈式css
爲何要有SpringBoot?html
簡化xml配置,提升開發效率。java
配置或者是YML文件mysql
SpringBoot 的做用web
簡化xml(除外mybatis)spring
獨立的應用程序(Jar/war(jsp))sql
單獨war工程-不須要集成tomcat插件運行。(內嵌入一個tomcat)數據庫
1. 建立獨立的 Spring 應用程序apache
2. 嵌入的 Tomcat,無需部署 WAR 文件json
3. 簡化 Maven 配置
4. 自動配置 Spring
5. 提供生產就緒型功能,如指標,健康檢查和外部配置
6.開箱即用,沒有代碼生成,也無需 XML 配置。
springboot 提供了 http refult風格
@RestController ==Controller每一個方法加上 @ResponseBody
@ResponseBody 返回 全部請求方法返回json格式。
你們本身在搭建環境的時候 寫請求裏面可能會發生如下異常。。
什麼是模板引擎?
動態頁面靜態---
什麼是動態頁面靜態化?
---搜索引擎,SEO -(僞靜態)html
jsp 經過servlet
分佈式事物解決方案
操做多個數據源事物解決方案
automatic+jta 兩段提交協議、 MQ推送。
--------------------------------------------------------------------------------------------------------
SpringBoot
1.一、SpringBoot簡介
在您第1次接觸和學習Spring框架的時候,是否由於其繁雜的配置而退卻了?在你第n次使用Spring框架的時候,是否以爲一堆反覆黏貼的配置有一些厭煩?那麼您就不妨來試試使用Spring Boot來讓你更易上手,更簡單快捷地構建Spring應用!
Spring Boot讓咱們的Spring應用變的更輕量化。好比:你能夠僅僅依靠一個Java類來運行一個Spring引用。你也能夠打包你的應用爲jar並經過使用java -jar來運行你的Spring Web應用。
Spring Boot的主要優勢:
爲全部Spring開發者更快的入門
開箱即用,提供各類默認配置來簡化項目配置
內嵌式容器簡化Web項目
沒有冗餘代碼生成和XML配置的要求
本章主要目標完成Spring Boot基礎項目的構建,而且實現一個簡單的Http請求處理,經過這個例子對Spring Boot有一個初步的瞭解,並體驗其結構簡單、開發快速的特性。
Java 7及以上
Spring Framework 4.1.5及以上
本文采用Java 1.8.0_7三、Spring Boot 1.3.2調試經過。
名爲」springboot-helloworld」 類型爲Jar工程項目
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> </parent> <dependencies> <!—SpringBoot web 組件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
|
spring-boot-starter-parent做用 在pom.xml中引入spring-boot-start-parent,spring官方的解釋叫什麼stater poms,它能夠提供dependency management,也就是說依賴管理,引入之後在申明其它dependency的時候就不須要version了,後面能夠看到。 spring-boot-starter-web做用 springweb 核心組件 spring-boot-maven-plugin做用 若是咱們要直接Main啓動spring,那麼如下plugin必需要添加,不然是沒法啓動的。若是使用maven 的spring-boot:run的話是不須要此配置的。(我在測試的時候,若是不配置下面的plugin也是直接在Main中運行的。)
|
2.三、編寫HelloWorld服務
建立package命名爲com.itmayiedu.controller(根據實際狀況修改)
建立HelloController類,內容以下
@RestController @EnableAutoConfiguration public class HelloController { @RequestMapping("/hello") public String index() { return "Hello World"; } public static void main(String[] args) { SpringApplication.run(HelloController.class, args); } } |
2.四、@RestController
在上加上RestController 表示修飾該Controller全部的方法返回JSON格式,直接能夠編寫
Restful接口
註解:做用在於讓 Spring Boot 根據應用所聲明的依賴來對 Spring 框架進行自動配置
這個註解告訴Spring Boot根據添加的jar依賴猜想你想如何配置Spring。因爲spring-boot-starter-web添加了Tomcat和Spring MVC,因此auto-configuration將假定你正在開發一個web應用並相應地對Spring進行設置。
標識爲啓動類
Springboot默認端口號爲8080
@RestController @EnableAutoConfiguration public class HelloController { @RequestMapping("/hello") public String index() { return "Hello World"; } public static void main(String[] args) { SpringApplication.run(HelloController.class, args); } } |
啓動主程序,打開瀏覽器訪問http://localhost:8080/index,能夠看到頁面輸出Hello World
@ComponentScan(basePackages = "com.itmayiedu.controller")---控制器掃包範圍
@ComponentScan(basePackages = "com.itmayiedu.controller") @EnableAutoConfiguration public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } } |
3.一、靜態資源訪問
在咱們開發Web應用的時候,須要引用大量的js、css、圖片等靜態資源。
默認配置
Spring Boot默認提供靜態資源目錄位置需置於classpath下,目錄名需符合以下規則:
/static
/public
/resources
/META-INF/resources
舉例:咱們能夠在src/main/resources/目錄下建立static,在該位置放置一個圖片文件。啓動程序後,嘗試訪問http://localhost:8080/D.jpg。如能顯示圖片,配置成功。
@ExceptionHandler 表示攔截異常
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) @ResponseBody public Map<String, Object> exceptionHandler() { Map<String, Object> map = new HashMap<String, Object>(); map.put("errorCode", "101"); map.put("errorMsg", "系統錯誤!"); return map; } } |
渲染Web頁面
在以前的示例中,咱們都是經過@RestController來處理請求,因此返回的內容爲json對象。那麼若是須要渲染html頁面的時候,要如何實現呢?
模板引擎
在動態HTML實現上Spring Boot依然能夠完美勝任,而且提供了多種模板引擎的默認配置支持,因此在推薦的模板引擎下,咱們能夠很快的上手開發動態網站。
Spring Boot提供了默認配置的模板引擎主要有如下幾種:
Spring Boot建議使用這些模板引擎,避免使用JSP,若必定要使用JSP將沒法實現Spring Boot的多種特性,具體可見後文:支持JSP的配置
當你使用上述模板引擎中的任何一個,它們默認的模板配置路徑爲:src/main/resources/templates。固然也能夠修改這個路徑,具體如何修改,可在後續各模板引擎的配置屬性中查詢並修改。
<!-- 引入freeMarker的依賴包. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> |
3.4.二、後臺代碼
在src/main/resources/建立一個templates文件夾,後綴爲*.ftl
@RequestMapping("/index") public String index(Map<String, Object> map) { map.put("name","美麗的天使..."); return "index"; } |
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title></title> </head> <body> ${name} </body> </html> |
3.4.四、Freemarker其餘用法
@RequestMapping("/index") public String index(Map<String, Object> map) { map.put("name","###螞蟻課堂###"); map.put("sex",1); List<String> userlist=new ArrayList<String>(); userlist.add("餘勝軍"); userlist.add("張三"); userlist.add("李四"); map.put("userlist",userlist); return "index"; } <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title>首頁</title> </head> <body> ${name} <#if sex==1> 男 <#elseif sex==2> 女 <#else> 其餘
</#if>
<#list userlist as user> ${user} </#list> </body> </html>
|
3.4.五、Freemarker配置
新建application.properties文件
######################################################## ###FREEMARKER (FreeMarkerAutoConfiguration) ######################################################## spring.freemarker.allow-request-override=false spring.freemarker.cache=true spring.freemarker.check-template-location=true spring.freemarker.charset=UTF-8 spring.freemarker.content-type=text/html spring.freemarker.expose-request-attributes=false spring.freemarker.expose-session-attributes=false spring.freemarker.expose-spring-macro-helpers=false #spring.freemarker.prefix= #spring.freemarker.request-context-attribute= #spring.freemarker.settings.*= spring.freemarker.suffix=.ftl spring.freemarker.template-loader-path=classpath:/templates/ #comma-separated list #spring.freemarker.view-names= # whitelist of view names that can be resolved |
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> </parent> <dependencies> <!-- SpringBoot 核心組件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> </dependencies> |
spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp |
@Controller public class IndexController { @RequestMapping("/index") public String index() { return "index"; } } |
4.一、springboot整合使用JdbcTemplate
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> |
4.1.2 application.properties新增配置
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
|
@Service public class UserServiceImpl implements UserService { @Autowired private JdbcTemplate jdbcTemplate; public void createUser(String name, Integer age) { System.out.println("ssss"); jdbcTemplate.update("insert into users values(null,?,?);", name, age); } } |
@ComponentScan(basePackages = "com.itmayiedu") @EnableAutoConfiguration public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
|
注意: spring-boot-starter-parent要在1.5以上
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.2.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> |
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
|
public interface UserMapper { @Select("SELECT * FROM USERS WHERE NAME = #{name}") User findByName(@Param("name") String name); @Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})") int insert(@Param("name") String name, @Param("age") Integer age); }
|
@ComponentScan(basePackages = "com.itmayiedu") @MapperScan(basePackages = "com.itmayiedu.mapper") @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } } |
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> |
@Entity(name = "users") public class User { @Id @GeneratedValue private Integer id; @Column private String name; @Column private Integer age; // ..get/set方法 } |
public interface UserDao extends JpaRepository<User, Integer> { } |
@RestController public class IndexController { @Autowired private UserDao userDao; @RequestMapping("/index") public String index(Integer id) { User findUser = userDao.findOne(id); System.out.println(findUser.getName()); return "success"; } } |
4.3.5 啓動項目
@ComponentScan(basePackages = { "com.itmayiedu" }) @EnableJpaRepositories(basePackages = "com.itmayiedu.dao") @EnableAutoConfiguration @EntityScan(basePackages = "com.itmayiedu.entity") public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } } |
同窗們思考下,大家在項目中有使用到多數據源嗎?
spring.datasource.test1.driverClassName = com.mysql.jdbc.Driver spring.datasource.test1.url = jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8 spring.datasource.test1.username = root spring.datasource.test1.password = root spring.datasource.test2.driverClassName = com.mysql.jdbc.Driver spring.datasource.test2.url = jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8 spring.datasource.test2.username = root spring.datasource.test2.password = root |
@Configuration // 註冊到springboot容器中 @MapperScan(basePackages = "com.itmayiedu.user1", sqlSessionFactoryRef = "test1SqlSessionFactory") public class DataSource1Config { /** * * @methodDesc: 功能描述:(配置test1數據庫) * @author: 餘勝軍 * @param: @return * @createTime:2017年9月17日 下午3:16:44 * @returnType:@return DataSource * @copyright:上海每特教育科技有限公司 * @QQ:644064779 */ @Bean(name = "test1DataSource") @Primary @ConfigurationProperties(prefix = "spring.datasource.test1") public DataSource testDataSource() { return DataSourceBuilder.create().build(); } /** * * @methodDesc: 功能描述:(test1 sql會話工廠) * @author: 餘勝軍 * @param: @param * dataSource * @param: @return * @param: @throws * Exception * @createTime:2017年9月17日 下午3:17:08 * @returnType:@param dataSource * @returnType:@return * @returnType:@throws Exception SqlSessionFactory * @copyright:上海每特教育科技有限公司 * @QQ:644064779 */ @Bean(name = "test1SqlSessionFactory") @Primary public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); // bean.setMapperLocations( // new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml")); return bean.getObject(); } /** * * @methodDesc: 功能描述:(test1 事物管理) * @author: 餘勝軍 * @param: @param * dataSource * @param: @return * @param: @throws * Exception * @createTime:2017年9月17日 下午3:17:08 * @returnType:@param dataSource * @returnType:@return * @returnType:@throws Exception SqlSessionFactory * @copyright:上海每特教育科技有限公司 * @QQ:644064779 */ @Bean(name = "test1TransactionManager") @Primary public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "test1SqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate( @Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } |
public interface User1Mapper { @Insert("insert into users values(null,#{name},#{age});") public int addUser(@Param("name") String name, @Param("age") Integer age); } |
4.4.3啓動項目
@ComponentScan(basePackages = "com.itmayiedu") @EnableAutoConfiguration public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
|
No qualifying bean of type [javax.sql.DataSource] is defined: expected single matching bean but found 2: test1DataSource,test2DataSource
5.1.1springboot整合事物管理
springboot默認集成事物,只主要在方法上加上@Transactional便可
使用springboot+jta+atomikos 分佈式事物管理
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jta-atomikos</artifactId> </dependency> |
# Mysql 1 mysql.datasource.test.url = jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8 mysql.datasource.test.username = root mysql.datasource.test.password = root mysql.datasource.test.minPoolSize = 3 mysql.datasource.test.maxPoolSize = 25 mysql.datasource.test.maxLifetime = 20000 mysql.datasource.test.borrowConnectionTimeout = 30 mysql.datasource.test.loginTimeout = 30 mysql.datasource.test.maintenanceInterval = 60 mysql.datasource.test.maxIdleTime = 60 mysql.datasource.test.testQuery = select 1 # Mysql 2 mysql.datasource.test2.url =jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8 mysql.datasource.test2.username =root mysql.datasource.test2.password =root mysql.datasource.test2.minPoolSize = 3 mysql.datasource.test2.maxPoolSize = 25 mysql.datasource.test2.maxLifetime = 20000 mysql.datasource.test2.borrowConnectionTimeout = 30 mysql.datasource.test2.loginTimeout = 30 mysql.datasource.test2.maintenanceInterval = 60 mysql.datasource.test2.maxIdleTime = 60 mysql.datasource.test2.testQuery = select 1
|
package com.itmayiedu.config; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "mysql.datasource.test") public class DBConfig1 { private String url; private String username; private String password; private int minPoolSize; private int maxPoolSize; private int maxLifetime; private int borrowConnectionTimeout; private int loginTimeout; private int maintenanceInterval; private int maxIdleTime; private String testQuery; } package com.itmayiedu.config; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "mysql.datasource.test1") public class DBConfig2 { private String url; private String username; private String password; private int minPoolSize; private int maxPoolSize; private int maxLifetime; private int borrowConnectionTimeout; private int loginTimeout; private int maintenanceInterval; private int maxIdleTime; private String testQuery; }
|
@Configuration // basePackages 最好分開配置 若是放在同一個文件夾可能會報錯 @MapperScan(basePackages = "com.itmayiedu.test01", sqlSessionTemplateRef = "testSqlSessionTemplate") public class TestMyBatisConfig1 { // 配置數據源 @Primary @Bean(name = "testDataSource") public DataSource testDataSource(DBConfig1 testConfig) throws SQLException { MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource(); mysqlXaDataSource.setUrl(testConfig.getUrl()); mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); mysqlXaDataSource.setPassword(testConfig.getPassword()); mysqlXaDataSource.setUser(testConfig.getUsername()); mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean(); xaDataSource.setXaDataSource(mysqlXaDataSource); xaDataSource.setUniqueResourceName("testDataSource"); xaDataSource.setMinPoolSize(testConfig.getMinPoolSize()); xaDataSource.setMaxPoolSize(testConfig.getMaxPoolSize()); xaDataSource.setMaxLifetime(testConfig.getMaxLifetime()); xaDataSource.setBorrowConnectionTimeout(testConfig.getBorrowConnectionTimeout()); xaDataSource.setLoginTimeout(testConfig.getLoginTimeout()); xaDataSource.setMaintenanceInterval(testConfig.getMaintenanceInterval()); xaDataSource.setMaxIdleTime(testConfig.getMaxIdleTime()); xaDataSource.setTestQuery(testConfig.getTestQuery()); return xaDataSource; } @Bean(name = "testSqlSessionFactory") public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "testSqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate( @Qualifier("testSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } package com.itmayiedu.datasource; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.atomikos.jdbc.AtomikosDataSourceBean; import com.itmayiedu.config.DBConfig1; import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource; @Configuration // basePackages 最好分開配置 若是放在同一個文件夾可能會報錯 @MapperScan(basePackages = "com.itmayiedu.test02", sqlSessionTemplateRef = "test2SqlSessionTemplate") public class TestMyBatisConfig2 { // 配置數據源 @Bean(name = "test2DataSource") public DataSource testDataSource(DBConfig1 testConfig) throws SQLException { MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource(); mysqlXaDataSource.setUrl(testConfig.getUrl()); mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); mysqlXaDataSource.setPassword(testConfig.getPassword()); mysqlXaDataSource.setUser(testConfig.getUsername()); mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean(); xaDataSource.setXaDataSource(mysqlXaDataSource); xaDataSource.setUniqueResourceName("test2DataSource"); xaDataSource.setMinPoolSize(testConfig.getMinPoolSize()); xaDataSource.setMaxPoolSize(testConfig.getMaxPoolSize()); xaDataSource.setMaxLifetime(testConfig.getMaxLifetime()); xaDataSource.setBorrowConnectionTimeout(testConfig.getBorrowConnectionTimeout()); xaDataSource.setLoginTimeout(testConfig.getLoginTimeout()); xaDataSource.setMaintenanceInterval(testConfig.getMaintenanceInterval()); xaDataSource.setMaxIdleTime(testConfig.getMaxIdleTime()); xaDataSource.setTestQuery(testConfig.getTestQuery()); return xaDataSource; } @Bean(name = "test2SqlSessionFactory") public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "test2SqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate( @Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } |
@EnableConfigurationProperties(value = { DBConfig1.class, DBConfig2.class })
#log4j.rootLogger=CONSOLE,info,error,DEBUG log4j.rootLogger=info,error,CONSOLE,DEBUG log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n log4j.logger.info=info log4j.appender.info=org.apache.log4j.DailyRollingFileAppender log4j.appender.info.layout=org.apache.log4j.PatternLayout log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n log4j.appender.info.datePattern='.'yyyy-MM-dd log4j.appender.info.Threshold = info log4j.appender.info.append=true #log4j.appender.info.File=/home/admin/pms-api-services/logs/info/api_services_info log4j.appender.info.File=/Users/dddd/Documents/testspace/pms-api-services/logs/info/api_services_info log4j.logger.error=error log4j.appender.error=org.apache.log4j.DailyRollingFileAppender log4j.appender.error.layout=org.apache.log4j.PatternLayout log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n log4j.appender.error.datePattern='.'yyyy-MM-dd log4j.appender.error.Threshold = error log4j.appender.error.append=true #log4j.appender.error.File=/home/admin/pms-api-services/logs/error/api_services_error log4j.appender.error.File=/Users/dddd/Documents/testspace/pms-api-services/logs/error/api_services_error log4j.logger.DEBUG=DEBUG log4j.appender.DEBUG=org.apache.log4j.DailyRollingFileAppender log4j.appender.DEBUG.layout=org.apache.log4j.PatternLayout log4j.appender.DEBUG.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n log4j.appender.DEBUG.datePattern='.'yyyy-MM-dd log4j.appender.DEBUG.Threshold = DEBUG log4j.appender.DEBUG.append=true #log4j.appender.DEBUG.File=/home/admin/pms-api-services/logs/debug/api_services_debug log4j.appender.DEBUG.File=/Users/dddd/Documents/testspace/pms-api-services/logs/debug/api_services_debug
|
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> |
@Aspect @Component public class WebLogAspect { private Logger logger = LoggerFactory.getLogger(getClass()); @Pointcut("execution(public * com.itmayiedu.controller..*.*(..))") public void webLog() { } @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 接收到請求,記錄請求內容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 記錄下請求內容 logger.info("URL : " + request.getRequestURL().toString()); logger.info("HTTP_METHOD : " + request.getMethod()); logger.info("IP : " + request.getRemoteAddr()); Enumeration<String> enu = request.getParameterNames(); while (enu.hasMoreElements()) { String name = (String) enu.nextElement(); logger.info("name:{},value:{}", name, request.getParameter(name)); } } @AfterReturning(returning = "ret", pointcut = "webLog()") public void doAfterReturning(Object ret) throws Throwable { // 處理完請求,返回內容 logger.info("RESPONSE : " + ret); } } |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> |
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"; updateCheck="false"> <diskStore path="java.io.tmpdir/Tmp_EhCache" /> <!-- 默認配置 --> <defaultCache maxElementsInMemory="5000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" memoryStoreEvictionPolicy="LRU" overflowToDisk="false" /> <cache name="baseCache" maxElementsInMemory="10000" maxElementsOnDisk="100000" /> </ehcache> |
配置信息介紹
@CacheConfig(cacheNames = "baseCache") public interface UserMapper { @Select("select * from users where name=#{name}") @Cacheable UserEntity findName(@Param("name") String name); } |
7.1.4清除緩存
@Autowired private CacheManager cacheManager; @RequestMapping("/remoKey") public void remoKey() { cacheManager.getCache("baseCache").clear(); }
|
在Spring Boot的主類中加入@EnableScheduling註解,啓用定時任務的配置
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("如今時間:" + dateFormat.format(new Date()));
}
}
啓動加上@EnableAsync ,須要執行異步方法上加入 @Async
配置文件值
name=itmayiedu.com |
配置文件值
@Value("${name}") private String name; @ResponseBody @RequestMapping("/getValue") public String getValue() { return name; } |
spring.profiles.active=pre |
application-dev.properties:開發環境 application-test.properties:測試環境 application-prod.properties:生產環境 |
8.五、修改端口號
server.port=8888
server.context-path=/itmayiedu
建立application.yml
server: port: 8090 context-path: /itmayiedu |
使用mvn package 打包
使用java –jar 包名
若是報錯沒有主清單,在pom文件中新增
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <maimClass>com.itmayiedu.app.App</maimClass> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> |