创建一个SpringBoot项目
创建项目注意点
然后选中自己需要的依赖 不过后期还可以自己导入不过比较麻烦
分析各种包
不过的文件夹需要自己建
图标写成这样放到public下面就会生成图标
favicon.ico
![](C:\Users\起个名字真难\AppData\Roaming\Typora\typora-user-images\image-20210721104059077.png
需要的依赖
首先这是一个web项目不过项目需要引入其他静态资源,所以还需要thymeleaf
所以需要这些依赖
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
org.thymeleaf
thymeleaf-spring5
org.thymeleaf.extras
thymeleaf-extras-java8time
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
页面跳转
和springMVC差不多
不过SpringBoot自带的有视图解析器他默认跳到的是 templates下的 XXX.html 要是有需求可以在application.properties下该
@Controller //这里要是 Controller
public class helloController {
//Ctrl+N看类的源码
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","你好");
List lists = new ArrayList();
lists.add("1111");
lists.add("222");
lists.add("333");
model.addAttribute("lists",lists);
return "test";
}
@RequestMapping("/login")
public String login(Model model){
return "login";
}
@RequestMapping("/welcome")
public String welcome(Model model, HttpServletRequest request){
String username = request.getParameter("username");
String password = request.getParameter("password");
model.addAttribute("msg",username);
return "welcome";
}
}
thymeleaf
导入thymeleaf依赖
也可以直接在创建springBoot项目的时候直接添加相关的依赖更简单
org.thymeleaf
thymeleaf-spring5
org.thymeleaf.extras
thymeleaf-extras-java8time
thymeleaf开发文档
主要的
test
Druid
这就是一个数据源 了解一下就好 主要还是看mybatis
简单用法
导入依赖 要是需要日志监控或者其他功能还需要导其他依赖
com.alibaba
druid
1.1.21
log4j
log4j
1.2.12
配置文件
application.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://localhost:3306/bookstore?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
type: com.alibaba.druid.pool.DruidDataSource
filter: stat,wall,log4j
配置DruidConfig
package com.hkd.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.zaxxer.hikari.util.DriverDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSour(){
return new DruidDataSource();
}
//后台监控
@Bean
public ServletRegistrationBean a(){
ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
HashMap map = new HashMap<>();
//设置账号密码
map.put("loginUsername","admin");
map.put("loginPassword","123456");
//允许谁访问 都可以访问
map.put("allow","");
bean.setInitParameters(map);
return bean;
}
}
然后访问到这 登录就进到监控页面了
SpringBoot整合Mybatis
先导入依赖
org.projectlombok
lombok
log4j
log4j
1.2.12
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.2.0
org.springframework.boot
spring-boot-starter-thymeleaf
2.4.3
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
写配置
application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/bookstore?serverTimezone=UTC&userUnicode=true&characterEncoding=UTF-8
#这个是别名
mybatis.type-aliases-package=com.example.pojo
#标明xml在哪 然后 他会在resourcest下 找所以要建一个文件夹专门放这些xml 注意mapper和xml要尽量写一致规范
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
在resourcest下建一个mybatis文件夹再在这个下面建一个mapper再写
SignonMapper.xml
select * from signon;
正常情况下mybatis要去扫描包什么的
这里要加一个注解 @Mapper
package com.example.mapping;
import com.example.pojo.Signon;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
//标明这是一个mybatis的mapper接口
@Mapper
@Repository
public interface SignonMapper {
List queryList();
Signon queryById(int id);
int add(Signon signon);
}
spring-Security
注意这个有版本问题版本太高会导致程序起不来
导入一个配置
org.springframework.boot
spring-boot-starter-security
1.5.13.RELEASE
写一个config
标明@EnableWebSecurity注解 继承WebSecurityConfigurerAdapter类
如果没有设置谁可以访问默认是都可以访问,只有设置了才会去拦截
package com.example.config;
/*
* 安全相当于不用写过滤器还有监听器了
* */
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//这个注解 继承WebSecurityConfigurerAdapter类
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//重写这个方法 这个相当于设计权限
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("login.html").permitAll()
.antMatchers("/three/**").permitAll() //这个都可以访问
.antMatchers("/one/**").hasRole("vip1") //有这个权限的才能访问里面的东西
.antMatchers("/two/**").hasRole("vip2");
//没有权限会跳到登录 他自定义的
// http.formLogin();
//定制登录页 这个是提交到哪 html页面的action
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
//注销 /logout 注销后到哪
http.logout().logoutSuccessUrl("/");
//记住我
// http.rememberMe(); //自定义的 相当于param名 然后写一个 checkbox name="rememberMe" 就行了
http.rememberMe().rememberMeParameter("rememberMe");
http.csrf().disable();//这个相当于关闭防火墙要不然自定义的不能用
}
//认证身份 也就是设置权限
//密码需要加密
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
.and()
.withUser("customer").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1") ;
}
}
具体登录页面
Title
账号:
密码:
记住我
关于角色信息的获取
@RequestMapping("/test")
public String aaa(Principal principal){
//通过这个方法可以获取springSecurity登录后的用户名
System.out.println(principal.getName());
//获取角色信息 看给的是什么
System.out.println(SecurityContextHolder.getContext().getAuthentication().getAuthorities());
return "test";
}
异步加载 Async
首先要是有个spring-boot项目
现在main里面开启异步加载
@EnableAsync //开启异步
@EnableAsync //开启异步
@SpringBootApplication
public class MissionApplication {
public static void main(String[] args) {
SpringApplication.run(MissionApplication.class, args);
}
}
然后再在要进行异步加载的方法体上加
@Async
@Async
public void aaa(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理完毕");
}
定时执行任务
1.先开启
@EnableScheduling //开启定时执行功能
@SpringBootApplication
public class MissionApplication {
public static void main(String[] args) {
SpringApplication.run(MissionApplication.class, args);
}
}
然后再在要进行定时任务的方法体上加
@Scheduled(cron = “0/4 * * ? “)
/*
自动生成 cron
https://cron.qqe2.com/
秒 分 时 日 月 周
0/4 * * * * ?
开始/步长 代表从几开始 每隔多久执行
a,b a和b的时候执行
4-7 4到7的时候执行 == 4,5,6,7
* 都包括
? 只能用在日或者月 因为日和周几有可能会冲突 基本上一个有值一个为?
*/
@Scheduled(cron = "0/4 * * * * ? ")
public void hello(){
System.out.println("被执行了");
}
发邮件
1.pom.xml上先导入依赖
org.springframework.boot
spring-boot-starter-mail
2.写配置
spring.mail.username=2353227567@qq.com
spring.mail.password=dqtvrcpmfvcxeabc
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true
然后选择两种方式,一种一般的另一种可以发附件的 注意导的包都是mail的别导错了
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
//简单的
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("测试");
mailMessage.setText("你的验证码是1123");
mailMessage.setTo("2353227567@qq.com");
mailMessage.setFrom("2353227567@qq.com");
mailSender.send(mailMessage);
}
@Test
void contextLoads2() throws MessagingException {
//复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("测试");
helper.setText("你的验证码是1123",true);
//添加附件 发过去的文件名 路径
helper.addAttachment("1.jpg",new File("D:\\桌面\\学习\\IDEA\\mission\\src\\main\\resources\\static\\img\\1.jpg"));
helper.addAttachment("2.jpg",new File("D:\\桌面\\学习\\IDEA\\mission\\src\\main\\resources\\static\\img\\1.jpg"));
helper.setTo("2353227567@qq.com");
helper.setFrom("2353227567@qq.com");
mailSender.send(mimeMessage);
}
swagger
就是有个扫描接口然后在网页上显示还可以对接口进行测试
先导入依赖
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
写配置项
一个docket相当于一个测试人员
@Configuration
@EnableSwagger2 //做标识
public class SwaggerConfig {
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("B");
}
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("李一博")
.select()
/*
RequestHandlerSelector扫描的方式
basePackage指定哪个包下
paths过滤什么路径
* */
.apis(RequestHandlerSelectors.basePackage("com.hkd.Controller"))
.paths(PathSelectors.ant("/hkd/**"))
.build();
}
public ApiInfo apiInfo(){
//作者信息
Contact contact = new Contact("李一博", "https://www.baidu.com/", "2353227567@qq.com");
//页面信息
return new ApiInfo("李一博的调试API文档",
"这是一个简单的Api 文档",
"1.0",
"urn:https://www.baidu.com/",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
然后可以在实体类上加注解到时候可以看见
//swaggrt里面可以看见
@ApiModel("用户实体类")
public class User {
@ApiModelProperty("用户名")
public String username;
@ApiModelProperty("密码")
public String password;
}
还可以在controller里面写
@ApiOperation("user2号")
@PostMapping("/user2")
public User Hello2(@ApiParam("名字") String name){
return new User();
}
分布式
初理解:
就有点像我在这个服务器上写的API接口什么的
然后你在另一个服务器上调用接口 通过RPC传递
RPC(Remote Procedure Call)远程过程调用,简单的理解是一个节点请求另一个节点提供的服务
再理解:
就是不同的任务(接口完成处理)然后放在不同的服务器上
然后所有的 接口什么的共同组成了一个项目
就是好多服务器一起做一个项目
因为数据量大然后 东西多 一个电脑干不了 或者性能不行
他们通过网络连接
这个有点像我想吃东西 吃最好的 这一顿想吃
北京:北京烤鸭、 天津:锅塌里脊、 河北:驴肉火烧、 山西:过油肉、等等
让这么多东西共同组成了一顿饭 不过这些东西分布在各处 所以就是分布式
zookeeper
就是注册中心
相当于快递公司
里面有两个店 一个发货 一个收货的
下载 里面的3.1
Dubbo基本使用与原理详解 – 云+社区 – 腾讯云 (tencent.com)
D:\桌面\学习\java\zookeeper\zookeeper-3.4.13\bin\zkServer.cmd 启动
刚安装会缺一个东西 在conf下
把zoo_sample.cfg复制一份改一下名 –>zoo.cfg
Dubbo
这是一个监控后台
这个优点像菜鸟裹裹看看我的快递 怎么样了、到哪了、怎么怎么着的
下载地址
https://github.com/apache/incubator-dubbo-ops
然后在根目录下进行打包 这个操作需要有maven切maven配置到环境变量里了
mvn clean package -Dmaven.test.skip=true
获得的jar就行了
同时启动zookeeper和dubbo
访问http://localhost:7001/就到了
默认账号密码root-root
整合Dubbo和Zookeeper
先启动zookeeper
然后运行jar包
java -jar jar包名
可能遇见的问题端口被占用
解决
netstat -ano | findstr 端口号
taskkill /f /pid 查询出来的id
访问
项目整合
提供者
org.apache.dubbo
dubbo-spring-boot-starter
2.7.3
com.github.sgroschupf
zkclient
0.1
log4j
log4j
org.apache.curator
curator-framework
2.12.0
org.apache.curator
curator-recipes
2.12.0
org.apache.zookeeper
zookeeper
3.4.14
org.slf4j
slf4j-log4j12
写核心配置文件
server.port=8001
#服务器应用名
dubbo.application.name=provide-service
#注册中心地址
dubbo.registry.address=zookeeper://127.0.0.1:2181
#扫描包 就是那些要被注册进去 肯定要加注解
dubbo.scan.base-packages=com.hkd.service
可能会报错 不过不影响 使用
写一个配置类 就解决了
log4j.properties
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
写提供者代码
注意要加在实现类上
@Service //dubbo的包
@Component //用dubbo最好别用Service
public class TicketServiceImpl implements TicketService{
@Override
public String getTicket() {
return "aasdasdasdsada";
}
}
运行项目
访问
消费者
导入相同的依赖
org.apache.dubbo
dubbo-spring-boot-starter
2.7.3
com.github.sgroschupf
zkclient
0.1
log4j
log4j
org.apache.curator
curator-framework
2.12.0
org.apache.curator
curator-recipes
2.12.0
org.apache.zookeeper
zookeeper
3.4.14
org.slf4j
slf4j-log4j12
然后写核心配置文件
server.port=8002
#去哪拿服务
dubbo.application.name=customer-service
#注册中心地址
dubbo.registry.address=zookeeper://127.0.0.1:2181
注意他们的端口号不一样
在相同的包下写相同的接口 就是把提供者的接口放在消费者里面相同的位置
写类 这个是类
这个注解可以理解为 @Autowired 不过他是远程的
@Reference //引用
TicketService ticketervice;
package com.hkd.service;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
/*
需要导同样的依赖
然后写配置文件
需要和提供的一样的接口 就负责过去 在同样的包下面
@Reference //引用
TicketService ticketervice;
写方法
ticketervice这个对象里面都有
*/
@Service //这个是托管给spring 导spring的包
public class UserService {
//要去注册中心拿
@Reference //引用
TicketService ticketervice;
public void buyTicket(){
String ticket = ticketervice.getTicket();
System.out.println("拿到:"+ticket);
}
}
然后直接用就好 前提是 zookeeper和dubbo还有提供者都打开了
@Autowired
UserService userService;
@Test
void contextLoads() {
userService.buyTicket();
}
Original: https://www.cnblogs.com/bxl-lyb/p/15074026.html
Author: 木子一十甫寸
Title: springboot小结
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/684917/
转载文章受原作者版权保护。转载请注明原作者出处!