spring全局配置
支援properties和yaml,但是名稱固定(約定大于配置)為:application
TIPS:yaml有個強大的地方就是它可以給實體類注入屬性
Tips:配置檔案還可以編寫占位符生成随機數

JSR303校驗
Springboot中可以用@validated來校驗資料
如果資料異常則會統一抛出異常,友善異常中心統一處理。
@NotNull(message="名字不能為空")
private String userName;
@Max(value=120,message="年齡最大不能查過120")
private int age;
@Email(message="郵箱格式錯誤")
private String email;
多配置切換
我們在主配置檔案編寫的時候,檔案名可以是 application-{profile}.properties/yml , 用來指定多個環境版本;
application-test.properties 代表測試環境配置
application-dev.properties 代表開發環境配置
#比如在配置檔案中指定使用dev環境,我們可以通過設定不同的端口号進行測試;
#我們啟動SpringBoot,就可以看到已經切換到dev下的配置了;(在主配置檔案下配置)
spring.profiles.active=dev
多文檔塊
和properties配置檔案中一樣,但是使用yml去實作不需要建立多個配置檔案,更加友善了 !
server:
port: 8081
#選擇要激活那個環境塊
spring:
profiles:
active: prod
--- #多文檔塊分隔符
server:
port: 8083
spring:
profiles: dev #配置環境的名稱
---
server:
port: 8084
spring:
profiles: prod #配置環境的名稱
spring的自動配置原理
SpringBoot啟動時會加載大量的自動配置類(/META-INF/spring.factories)
如果是标了@Configuration注解,就是批量加載了裡面的bean定義,隻要有寫好的配置檔案spring.factories就實作了自動。
但是配置類不一定生效,要判斷條件是否成立,隻要導入了對應的starter(啟動器),當有啟動器且條件成立,我們的自動裝配才會啟動!!(其實啟動器也是條件的一部分。。)
SpringSecurity
重要的類:
WebSecurityConfigurerAdapter 自定義Security政策
AuthenticationManagerBuilder 自定義認證政策
@EnableWebSecurity 開啟WebSecurity子產品
目标:“認證”、“授權”
“認證”(Authentication)
身份驗證是關于驗證您的憑據,如使用者名/使用者ID和密碼,以驗證您的身份。
身份驗證通常通過使用者名和密碼完成,有時與身份驗證因素結合使用。
“授權” (Authorization)
授權發生在系統成功驗證您的身份後,最終會授予您通路資源(如資訊,檔案,資料庫,資金,位置,幾乎任何内容)的完全權限。
這個概念是通用的,而不是隻在Spring Security 中存在。
//AOP : 攔截器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 鍊式程式設計
@Override
//授權
protected void configure(HttpSecurity http) throws Exception {
//首頁所有人可以通路,功能頁隻有對應有權限的人才能通路
//請求授權的規則
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//沒有權限預設會到登入頁面,需要開啟登入的頁面
http.formLogin()
.loginPage("/toLogin")
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/login");
http.csrf().disable();//關閉csrf功能:跨站請求僞造,預設隻能通過post方式送出logout請求
// 開啟登出功能
http.logout().logoutSuccessUrl("/");
//開啟記住我功能
http.rememberMe().rememberMeParameter("rememberme");
}
//認證
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//在記憶體中定義,也可以在jdbc中去拿....
//Spring security 5.0中新增了多種加密方式,也改變了密碼的格式。
//要想我們的項目還能夠正常登陸,需要修改一下configure中的代碼。我們要将前端傳過來的密碼進行某種方式加密
//spring security 官方推薦的是使用bcrypt加密方式。
//使用者權限設定!
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("xiaozhu").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
Shiro(也是JAVA安全架構)
應用安全的四大基石:認證、授權、會話管理、加密
shiro架構有三個重要的理念:
Subject 使用者
SecurityManager 管理使用者
Realm 連接配接資料
shrio的quickstart
SecurityUtils.getSubject() 獲得目前使用者對象
currentUser.getSession() 通過使用者拿到緩存
currentUser.isAuthenticated() 判斷使用者是否被授權
currentUser.getPrincipal() 獲得授權
currentUser.hasRole("AAA") 測試角色
currentUser.isPermitted("") 判斷權限,設定權限
currentUser.logout(); 登出
SpringBoot內建Shiro
①導入依賴
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.3</version>
</dependency>
②自定義UserRealm類
public class UserRealm extends AuthorizingRealm {
//授權
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
return null;
}
}
③編寫Shiro配置類
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean ③
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManger") DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//關聯DefaultWebSecurityManager(設定安全管理器)
bean.setSecurityManager(securityManager);
//添加shiro的内置過濾器
/*
* anno : 無需認證就可以通路
* authc: 必須認證了才能通路
* user: 必須擁有(記住我)功能才能通路
* perms:擁有對某個資源的權限才能通路
* role:擁有某個角色權限才能通路
*/
//攔截
Map<String, String> filterMap = new LinkedHashMap<>();
//授權
filterMap.put("/book/add","perms[book:add]");
filterMap.put("/book/update","perms[book:update]");
bean.setFilterChainDefinitionMap(filterMap);
//如果沒有權限,調到login頁面
bean.setLoginUrl("/login");
//設定未授權頁面
bean.setUnauthorizedUrl("/noauth");
return bean;
}
//DefaultWebSecurityManager ②
@Bean(name="securityManger")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//關聯UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//建立realm對象,需要自定義類 ①
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
}
Swagger
- 号稱世界上最流行的API架構;
- RestFul Api文檔線上自動生成工具 => Api文檔與Api定義同步更新
- 直接運作,可以線上測試API接口
- 支援多種語言:(Java , Php…)
①導入依賴
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
②配置swagger的作者資訊
@Configuration
@EnableSwagger2 //開啟Swagger
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
//配置Swagger的資訊=apiInfo
public ApiInfo apiInfo(){
//作者資訊
Contact contact = new Contact("Daniel","https://www.baidu.com","[email protected]");
return new ApiInfo("Dainel的SwaggerAPI文檔",
"天道酬勤",
"v1.0",
"urn:tos",
contact, "Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
③配置Swagger的掃描接口
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select()
//RequestHandlerSelectors,配置要掃描接口的方式
//basePackage,指定要掃描的包
//any(): 掃描全部
.apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
.paths(PathSelectors.ant("/kuang/**"))
.build();
}
④配置環境
@Bean
public Docket docket(Environment environment){
//設定要顯示的Swagger環境
Profiles profiles = Profiles.of("dev","test");
//通過 environment.acceptsProfiles 判斷是否處在自己設定的環境中
boolean flag = environment.acceptsProfiles(profiles);
...
}
注釋的注解
任務
異步任務
①在要執行異步任務的方法上加注解@Async
②在main方法上加@EnableAsync開啟異步任務注解
郵件任務
①導spring-boot-starter-mail包
②SimpleMailMessage對象中的各個方法(簡單郵件)
③application配置檔案中配置郵箱屬性
[email protected]
spring.mail.password=aaaaaaaa
spring.mail.host=smtp.qq.com
# 開啟加密驗證
spring.mail.properties.mail.smtp.ssl.enable=true
定時任務
TaskScheduler 任務排程者
TaskExecutor 任務執行者
@EnableScheduling 開啟定時功能的注解
@Scheduled 什麼時候執行
Cron表達式
①編寫定時任務
@Service
public class ScheduledService {
//在一個特定的時間執行這個方法
@Scheduled(cron = "30 17 17 * * ?")
public void Hello(){
System.out.println("hello,被執行了!");
}
}
②啟動類配置
@EnableAsync // 開啟異步注解功能
@EnableScheduling //開啟定時功能的注解
@SpringBootApplication
public class Springboot09TaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09TaskApplication.class, args);
}
}
Dubbo+Zookeeper+Springboot(不知道不了解,都是copy的。。以後再補)
Dubbo是一款高性能、輕量級的開源Java RPC架構,它提供了三大核心能力:面向接口的遠端方法調用,智能容錯和負載均衡,以及服務自動注冊和發現。
服務提供者(Provider):暴露服務的服務提供方,服務提供者在啟動時,向注冊中心注冊自己提供的服務。
服務消費者(Consumer):調用遠端服務的服務消費方,服務消費者在啟動時,向注冊中心訂閱自己所需的服務,服務消費者,從提供者位址清單中,基于軟負載均衡算法,選一台提供者進行調用,如果調用失敗,再選另一台調用。
注冊中心(Registry):注冊中心傳回服務提供者位址清單給消費者,如果有變更,注冊中心将基于長連接配接推送變更資料給消費者
監控中心(Monitor):服務消費者和提供者,在記憶體中累計調用次數和調用時間,定時每分鐘發送一次統計資料到監控中心
分布式架構會遇到的四個核心問題
這麼多服務,用戶端該如何去通路
這麼多服務,服務之間如何進行通信
這麼多服務,如何管理
服務挂了,該怎麼辦
解決方法==》 SpringCloud