SpringBoot学习笔记
1.使用idea骨架直接创建SpringBoot程序
2.使用官网创建https://start.spring.io/
3.使用阿里的网站创建https://start.aliyun.com/
在没有网络的时候自己搭建(前提是本地仓库有依赖文件)
//继承版本控制
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.11</version>
</parent>
//web程序的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
//程序的启动入口
@SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
}
忽略不想看到的的文件小方法
在setting设置中有一个file types设置里面有忽略文件的后缀
setting -> file types -> ignored files and folders
SpringBoot的优点
- 简化了Spring的开发
- 内置tomcat服务器等
- 版本控制
引导类
启动springboot的入口(也是一个配置类)
@SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
}
内嵌tomcat服务器
实际上是将tomcat服务注册成一个bean交给spring管理这样就实现了不用自己配置tomcat服务器
排除依赖
//排除依赖
<exclusions>
<exclusion>
<groupId></groupId>
<artifactId></artifactId>
</exclusion>
</exclusions>
REST风格的开发方式
- 书写简化代码
- 外部不知道进行什么操作(保密性高)
- 根据请求方式进行业务操作
- GET
- POST
- PUT
- DELETE等等
SpringBoot配置怎么写
-
使用application.properties配置文件修改配置
#修改端口 server.port=80 #修改启动配置 spring.main.banner-mode=off #日志的级别 logging.level.root=error
-
使用yaml文件格式来配置(重数据轻格式)
server: port: 80 spring: main: banner-mode: off
-
使用yml文件格式来配置(主流配置文件)
server: port: 80 spring: main: banner-mode: off
-
具体格式要求
-
数据与属性之间要有一个空格分隔
-
层级关系一层一层嵌套
-
#表示注释
#表示注释 server: port: 80 spring: main: banner-mode: off #user对象数组 user: [{name:zyl,age:18},{name:zs,age:11}]
可以读取配置文件
@Component //读取数据 @ConfigurationProperties("datasource") public class Mydata { private String driver; private String url; private String username; private String password; public Mydata() { } public Mydata(String driver, String url, String username, String password) { this.driver = driver; this.url = url; this.username = username; this.password = password; } /** * 获取 * @return driver */ public String getDriver() { return driver; } /** * 设置 * @param driver */ public void setDriver(String driver) { this.driver = driver; } /** * 获取 * @return url */ public String getUrl() { return url; } /** * 设置 * @param url */ public void setUrl(String url) { this.url = url; } /** * 获取 * @return username */ public String getUsername() { return username; } /** * 设置 * @param username */ public void setUsername(String username) { this.username = username; } /** * 获取 * @return password */ public String getPassword() { return password; } /** * 设置 * @param password */ public void setPassword(String password) { this.password = password; } public String toString() { return "Mydata{driver = " + driver + ", url = " + url + ", username = " + username + ", password = " + password + "}"; } }
SpringBoot整合Junit
//导入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
//测试类 @SpringBootTest class Demo1ApplicationTests { @Test void contextLoads() { System.out.println("hello springboot"); } }
SpringBoot整合Mybatis
1.导入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
2.编写Dao层接口
@Mapper public interface UserDao { List<User>getAll(); @Select("select * from user where id=#{id}") User getById(int id); }
3.配置文件的sql语句(复杂的sql语句)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zyl.Dao.UserDao"> <select id="getAll" resultType="com.zyl.Pojo.User"> select * from user </select> </mapper>
4.业务层接口
public interface UserService { List<User> getAll(); User getById(int id); }
5.业务层实现类
@Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public List<User> getAll() { List<User> users = userDao.getAll(); return users; } @Override public User getById(int id) { return userDao.getById(id); } }
6.实现类
@SpringBootTest class Demo1ApplicationTests { @Autowired private UserService userService; @Test void contextLoads() { List<User> users = userService.getAll(); System.out.println(users); } @Test void getById() { int id=1; System.out.println(userService.getById(id)); } }
-
SpringBoot整合MybatisPlus
1.导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.数据层接口(继承接口简化开发)
@Mapper
public interface UserDao extends BaseMapper<User> {
}
3.实体类
package com.mybatisplus.Pojo;
public class User {
private int id;
private String name;
public User() {
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
/**
* 获取
* @return id
*/
public int getId() {
return id;
}
/**
* 设置
* @param id
*/
public void setId(int id) {
this.id = id;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
public String toString() {
return "User{id = " + id + ", name = " + name + "}";
}
}
4.测试类
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
User user = userDao.selectById(1);
System.out.println(user);
}
}
SpringBoot整合Druid
1.导入坐标
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.配置文件
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8&useSSL=true
username: root
password: 123456
3.测试类和Mybatis一样
使用lombok加速实体类开发
1.导入坐标
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
2.简介
//这个注解提供了了相应的get set tostring等方法
@Data
public class Book {
private Integer id;
private String type;
private String name;
private String description;
}
怎么配置MybatisPlus运行日志
配置分页功能拦截器
-
@Configuration public class MPConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(){ MybatisPlusInterceptor interceptor=new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); return interceptor; } }
-
测试类
@Test void selectByPage(){ IPage page=new Page(4,3); userdao.selectPage(page,null); }
按条件查询
-
测试类
@Test void selectBycondition1(){ QueryWrapper<User> qw=new QueryWrapper<>(); qw.like("name","你"); userdao.selectList(qw); }
-
优化查询(防止写错字段名)
@Test void selectBycondition2(){ LambdaQueryWrapper<User> qw=new LambdaQueryWrapper<>(); qw.like(User::getName,"杀"); userdao.selectList(qw); }
-
Springboot运维及上线
1.怎么打包
-
使用maven打包工具
-
打包后可以在装有java运行环境的所有机器上运行
-
运行命令是
java -jar 打包名.jar
-
注意点是导入打包工具
<plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins>
2.linux下怎么运行
-
运行命令是
java -jar 打包名.jar
3.使用临时属性启动SpringBoot
例如
java -jar 打包名.jar --server.port=自己想要用的端口
4.下面的(args)参数表示临时属性 去掉这个参数比较安全
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
SpringBoot的四级配置文件及意义
一级 file : config/application.yml (最高级别保密等级高)
二级 file : application.yml
三级 classpath : config/application.yml
四级 classpath : application.yml (最低 一般是程序员使用)
自定义配置文件
在参数里面加上配置文件的名字
--spring.config.name=文件名
多环境开发
#使用哪个环境
spring:
profiles:
active: test
---
#生产环境
spring:
profiles: product
server:
port: 80
---
#开发环境
spring:
profiles: develement
server:
port: 81
---
#测试环境
spring:
profiles: test
server:
port: 82
设置运行日志
1.方式一
//创建记录日志的对象
private static final Logger log= LoggerFactory.getLogger(UserController.class);
2.方式二(使用lombok使用时添加@Slf4j)
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
热部署
导入依赖(需要开启热部署)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
怎么在测试类里面测试web层
1.开启虚拟MVC调用(在测试类加上注解)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class LoginApplicationTests {
@Test
public void testWeb(@Autowired MockMvc mockMvc) throws Exception {
//创建虚拟请求,访问/users
MockHttpServletRequestBuilder builder= MockMvcRequestBuilders.get("/users");
//执行操作
ResultActions perform = mockMvc.perform(builder);
//测试定义预期值
StatusResultMatchers status = MockMvcResultMatchers.status();
//定义200状态码
ResultMatcher ok = status.isOk();
//比对
perform.andExpect(ok);
}
//测试响应体是否匹配
@Test
public void testBody(@Autowired MockMvc mockMvc) throws Exception {
//创建虚拟请求,访问/users
MockHttpServletRequestBuilder builder= MockMvcRequestBuilders.get("/users");
//执行操作
ResultActions perform = mockMvc.perform(builder);
//测试定义预期值
ContentResultMatchers content = MockMvcResultMatchers.content();
//定义200状态码
ResultMatcher s = content.string("s");
//比对
perform.andExpect(s);
}
}
测试类数据不添加到数据库
//t
@Transactional
SpringBoot内置数据库
1.H2
导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>H2</artifactId>
<version>2.1.4</version>
</dependency>
2.Redis(nosql数据库)
导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Elasticsearch(分布式搜索引擎)
1.创建索引
//以PUT方式提交就表示创建了一个以users的索引 查询则是以get请求方式 删除是delete请求方式
http://localhost:9200/users
2.IK分词器
//设置分词器
{
"mappings":{
"properties":{
"id":{
"type":"keyword"
},
"name":{
"type":"text",
"analyzer":"ik_max_word",
"copy_to":"all"
},
"address":{
"type":"text",
"analyzer":"ik_max_word",
"copy_to":"all"
},
"all":{
"type":"text",
"analyzer":"ik_max_word"
}
}
}
}
3.Elasticsearch的使用操作文档
-
按文档插入(不指定id自动生成)(put)
http://localhost:9200/users/_doc
-
生成id为1的信息(put)
http://localhost:9200/users/_doc/1
-
_create/id(生成id为1的信息)(put)
http://localhost:9200/users/_create/1
-
查询单个(get)
http://localhost:9200/users/_doc/1
-
查询全部(get)
http://localhost:9200/users/_search
-
条件查询
http://localhost:9200/users/_search?q=字段名:值
-
根据id更新(覆盖所有意思是没修改的字段信息就删除了)
http://localhost:9200/users/_doc/1
-
部分修改(操作文档属性)
http://localhost:9200/users/_update/1 { "doc":{ "字段":"值" } }
SpringBoot整合Elasticsearch
低版本客户端
-
导入坐标
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
-
配置
spring: elasticsearch: rest: uris: http://localhost:9200
-
创建对象
//创建es客户端对象 private ElasticsearchRestTemplate template;
高版本客户端
-
导入坐标
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> </dependency>
-
配置
HttpHost host=HttpHost.create("http://localhost:9200"); RestClientBuilder builder = RestClient.builder(host); client=new RestHighLevelClient(builder); client.close();
-
测试
//初始化客户端 HttpHost host=HttpHost.create("http://localhost:9200"); RestClientBuilder builder = RestClient.builder(host); client=new RestHighLevelClient(builder); CreateIndexRequest requset=new CreateIndexRequest("books"); client.indices().create(requset, RequestOptions.DEFAULT); //关闭客户端 client.close();
使用mybatis测试数据加入文档
@BeforeEach
void setUp() {
HttpHost host=HttpHost.create("http://localhost:9200");
RestClientBuilder builder = RestClient.builder(host);
client=new RestHighLevelClient(builder);
}
@AfterEach
void tearDown() throws IOException {
client.close();
}
List<User> users = userdao.selectList(null);
BulkRequest request=new BulkRequest();
for (User user : users) {
IndexRequest req=new IndexRequest("books").id(user.getId().toString());
String json= JSON.toJSONString(user);
req.source(json,XContentType.JSON);
request.add(req);
}
client.bulk(request,RequestOptions.DEFAULT);
根据id查询
GetRequest request=new GetRequest("books","3");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
String str = response.getSourceAsString();
System.out.println(str);
根据条件查询
//访问索引
SearchRequest request=new SearchRequest("books");
//查询条件
SearchSourceBuilder builder=new SearchSourceBuilder();
builder.query(QueryBuilders.termQuery("username","zyl"));
request.source(builder);
//调用serach相关的api
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
//遍历数据
for (SearchHit hit : hits) {
String source = hit.getSourceAsString();
System.out.println(source);
}
根据Id删除
DeleteRequest request=new DeleteRequest("books","1");
DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
System.out.println(delete.toString());
缓存
定义:缓存是一种介于永久存储介质和数据应用之间的数据临时存储介质
意义:一般是减少数据库的压力减少磁盘io
使用示例
导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
//启动类加上下面的注解
@EnableCaching
//在需要加入缓存的地方加上如下信息 value名称空间 key表示可以取的唯一id
@Cacheable(value = "cache",key = "#id")
@cacheput //表示加入缓存
变更Ehcache缓存
导入坐标
<!--缓存坐标-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
SpringBoot更换默认缓存
spring:
cache:
type: ehcache
配置文件
<?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="D://tools"/>
<cache
name="phoneCode"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="10"
timeToLiveSeconds="10"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
变更Redis缓存
Jetcache的使用
导入坐标
<dependency>
<groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redis</artifactId>
<version>2.6.2</version>
</dependency>
设置
jetcache:
remote:
default:
type: redis
host: localhost
port: 6379
poolConfig:
maxTotal: 50
使用
package com.zyl;
import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//jetcache开启缓存的配置
@EnableCreateCacheAnnotation
public class DemoJetcacheApplication {
public static void main(String[] args) {
SpringApplication.run(DemoJetcacheApplication.class, args);
}
}
@Autowired
private UserService userService;
@CreateCache(name = "jetcache",expire = 3600)
private Cache<String,String> jetcache;
@GetMapping("{phone}")
public String getAll(@PathVariable String phone){
String code = userService.getCode(phone);
jetcache.put(phone,code);
String s = jetcache.get(phone);
return code;
}
对方法的操作缓存
配置
jetcache:
remote:
default:
type: redis
host: localhost
port: 6379
keyConvertor: fastjson
valueEncode: java
vaueDecode: java
poolConfig:
maxTotal: 50
使用
package com.zyl;
import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
import com.alicp.jetcache.anno.config.EnableMethodCache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//jetcache开启缓存的配置
@EnableCreateCacheAnnotation
//开启方法注解
@EnableMethodCache(basePackages = "com.zyl")
public class DemoJetcacheApplication {
public static void main(String[] args) {
SpringApplication.run(DemoJetcacheApplication.class, args);
}
}
SpringBoot整合Quartz
导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
定时执行的任务
package com.zyl.quartz;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class Myquartz extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("quartz is runing");
}
}
配置类
package com.zyl.config;
import com.zyl.quartz.Myquartz;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class QuartzConfig {
@Bean
public JobDetail printJobDetail(){
//绑定具体工作
return JobBuilder.newJob(Myquartz.class).storeDurably().build();
}
@Bean
public Trigger printTriger(){
//绑定对应的工作明细
ScheduleBuilder scheduleBuilder=CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
return TriggerBuilder.newTrigger().forJob(printJobDetail()).withSchedule(scheduleBuilder).build();
}
}
加速开发
package com.zyl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
//开启定时任务
@EnableScheduling
public class DemoTaskApplication {
public static void main(String[] args) {
SpringApplication.run(DemoTaskApplication.class, args);
}
}
package com.zyl.quartz;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Mybean {
@Scheduled(cron="0/1 * * * * ?")
public void get(){
System.out.println("spring task is runing");
}
}
SpringBoot整合javaMail
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
package com.zyl.Service.Impl;
import com.zyl.Service.SendMail;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
@Service
public class SendMailImpl implements SendMail {
@Autowired
private JavaMailSender javaMailSender;
private String from="203094041@qq.com";
private String to="2722820199@qq.com";
private String subject="测试";
private String context="5";
@Override
public void sendMail() throws MessagingException {
// SimpleMailMessage message = new SimpleMailMessage();
// message.setFrom(from);
// message.setTo(to);
// message.setSubject(subject);
// message.setText(context);
// javaMailSender.send(message);
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
helper.setFrom(from+"(宝贝)");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(context,true);
javaMailSender.send(mimeMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
配置
spring:
mail:
host: smtp.qq.com
username: 203094041@qq.com
password: zaeaagitxziybgbi
消息
JMS:一种消息服务的规范就像JDBC规范
AMQP:高级消息队列协议
SpringBoot整合activemq
导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
配置
server:
port: 80
spring:
activemq:
broker-url: tcp://localhost:61616
jms:
template:
default-destination: zyl
演示
package com.zyl.Service.Impl;
import com.zyl.Service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@Service
public class MessageServiceImpl implements MessageService {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Override
public void SendMessage(String id) {
System.out.println("加入处理队列:" + id);
jmsMessagingTemplate.convertAndSend("order.queue.id",id);
}
@Override
public String DoMessage() {
String id = jmsMessagingTemplate.receiveAndConvert(String.class);
System.out.println("已完成短信发送业务:"+id);
return id;
}
}
监听器
package com.zyl.Service.Listener;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;
@Component
public class MsgListener {
@JmsListener(destination = "order.queue.id")
public void recive(String id){
System.out.println("监听器:"+id);
}
}
转发监听
package com.zyl.Service.Listener;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;
@Component
public class MsgListener {
@JmsListener(destination = "order.queue.id")
@SendTo("orther.id")
public String recive(String id){
System.out.println("监听器:"+id);
return "new"+id;
}
}
SpringBoot整合Rabbitmq
导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置
server:
port: 80
spring:
rabbitmq:
host: localhost
port: 5672
演示
直连配置类
package com.zyl.Service.Impl.Rabbitmq.direct.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class rabbitConfig {
//队列配置
@Bean
public Queue DirectQueue(){
return new Queue("direct_queue",true,true,true);
}
//交换机配置
@Bean
public DirectExchange directExchange(){
return new DirectExchange("directExchange");
}
//绑定
@Bean
public Binding bindingDirect(){
return BindingBuilder.bind(DirectQueue()).to(directExchange()).with("direct");
}
}
package com.zyl.Service.Impl.Rabbitmq.direct;
import com.zyl.Service.MessageService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class rabbitmqDirectImpl implements MessageService {
@Autowired
private AmqpTemplate amqpTemplate;
@Override
public void SendMessage(String id) {
System.out.println("加入处理队列(rabbitmq direct):" + id);
amqpTemplate.convertAndSend("directExchange","direct",id);
}
@Override
public String DoMessage() {
return null;
}
}
监控
导入SpringBoot管理坐标
服务端
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.5.4</version>
</dependency>
开启监控
package com.zyl;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableAdminServer
public class DemoAdminApplication {
public static void main(String[] args) {
SpringApplication.run(DemoAdminApplication.class, args);
}
}
客户端
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.5.4</version>
</dependency>
配置
spring:
boot:
admin:
client:
url: http://localhost:8080
server:
port: 88
management:
endpoint:
health:
show-details: always
endpoints:
web:
exposure:
include: "*"
SpringBoot原理
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--自定义bean-->
<bean id="cat" class="com.zyl.bean.Cat"/>
<bean id="mouse" class="com.zyl.bean.Mouse"/>
<!--管理第三方bean-->
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource"/>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
>
<!--指定bean的加载空间,component-->
<context:component-scan base-package="com.zyl.bean"/>
</beans>
使用注解加载xml配置文件(系统迁移)
package com.zyl.config;
import org.springframework.context.annotation.ImportResource;
@ImportResource("applicationContext.xml")
public class SpringConfig {
}
//表示拿到是非单例对象 t
@Configuration(proxyBeanMethods = false)
自动配置
技术集---->设置集---->初始化环境
自定义starter
ipAutoConfigration配置类
package com.zyl.Autoconfig;
import com.zyl.Properties.ipProperties;
import com.zyl.Service.ipService;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@EnableConfigurationProperties(ipProperties.class)
public class ipAutoConfigration {
@Bean
public ipService ipService(){
return new ipService();
}
}
读取配置文件
package com.zyl.Properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "tools.ip")
public class ipProperties {
/*
* 日志显示周期
* */
private long cycle=5L;
/*
* 是否周期内重置数据
* */
private boolean cycleReset=false;
/*
* 日志输出模式detail simple
* */
private String model=LogModel.DETAIL.value;
public enum LogModel{
DETAIL("detail"),
SIMPLE("simple");
private String value;
public String getValue() {
return value;
}
LogModel(String value) {
this.value = value;
}
}
public long getCycle() {
return cycle;
}
public void setCycle(long cycle) {
this.cycle = cycle;
}
public boolean isCycleReset() {
return cycleReset;
}
public void setCycleReset(boolean cycleReset) {
this.cycleReset = cycleReset;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
业务层
package com.zyl.Service;
import com.zyl.Properties.ipProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
public class ipService {
//创建map
private Map<String,Integer>ipCount=new HashMap<>();
//创建request对象
@Autowired
private HttpServletRequest httpServletRequest;
public void count(){
//获取当前ip
String ip=httpServletRequest.getRemoteAddr();
//根据ip自增或者创建新的访问
Integer count = ipCount.get(ip);
if (count==null){
ipCount.put(ip,1);
}else {
ipCount.put(ip,count+1);
}
}
@Autowired
private ipProperties ipProperties;
@Scheduled(cron = "0/${tools.ip.cycle:5} * * * * ?")
public void print(){
if (ipProperties.getModel().equals(com.zyl.Properties.ipProperties.LogModel.DETAIL.getValue())){
System.out.println("访问量监控系统");
System.out.println("+-------ip地址--------+--次数--+");
for (Map.Entry<String, Integer> entry : ipCount.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(String.format("|%-18s |%5d |",key,value));
}
}else if (ipProperties.getModel().equals(com.zyl.Properties.ipProperties.LogModel.SIMPLE.getValue())){
System.out.println("简单访问量监控系统");
System.out.println("+-------ip地址----------+");
for (Map.Entry<String, Integer> entry : ipCount.entrySet()) {
String key = entry.getKey();
System.out.println(String.format("|%-18s |",key));
}
}
System.out.println("+-----------------------------+");
//是否清除数据
if (ipProperties.isCycleReset()){
ipCount.clear();
}
}
public static void main(String[] args) {
ipService ipService = new ipService();
ipService.print();
}
}
制作yml提示功能
导入坐标
<dependency>s
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
SpringBoot的启动流程
- 初始化数据,加载为对象
- 读取环境信息
- 系统设置
- 参数等
- 创建Spring容器对象ApplicationContext
- 通过监听器机制,加载不同的阶段数据,更新数据的需求
启动过程
- primarySources
- 启动类