笔者自学的框架,知识点来自网上学习教程,方便实惠,推荐,特此声明。
(但是没有很多细节,真的很伤啊学起来)
sringboot官网
- springbootGitHub地址:https://github.com/spring-projects/spring-boot
- springboot官方文档:https://spring.io/guides/gs/spring-boot
springboot配置文件
- pom.xml
springboot热部署
使得springboot支持jsp,让springboot编译webapp下文件,同时在Project Structure中设置web.xml<!-- springboot 开发自动热部署 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>
在built标签下加入<!--springboot tomcat jsp 支持开启--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <scope>compile</scope> </dependency>
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/**</include> </includes> </resource> <resource> <directory>src/main/webapp</directory> <targetPath>META-INF/resources</targetPath> <includes> <include>**/**</include> </includes> </resource> </resources>
- application.properties
例可以设置几种不同的环境#字符编码位置要放到下面中文的上面,下面是指定字符编码 spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true #修改内置tomcat端口号 server.port=8080 #设置项目上下文 server.servlet.context-path=/myspringboot #设置开发环境得配置文件,优先级比application.properties高 spring.profiles.active=dev #自定义配置 author.name=java author.address=广东 author.age=18
让springboot支持jsp开发环境:application-dev.properties 测试环境:application-test.properties 生产环境:application-online.properties
spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp #这个是关闭thymeleaf缓存,不是很必要 spring.thymeleaf.cache=false #关闭thymeleaf模板,不是很必要 spring.thymeleaf.enabled = false
springboot注解
- @SpringBootApplication
里面的@SpringBootApplication注解是springboot的核心注解,主要作用是开启spring自动配置。使用这个注解相当于加上了下面三个注解:- @Configuration 允许将其他@bean注解标识的类加入到spring容器中,相当于spring配置文件中的beans标签
- @EnableAutoConfiguration 启动自动配置
- @ComponentScan 会自动扫描当前包和子包下的标有@Component,@Service,@Repository,@Controller的类。相当于以前spring配置文件中的context:component-scan
- @RequestParam @RequestBody 总结 总结来源
- @RequestParam
用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)
RequestParam可以接受简单类型的属性,也可以接受对象类型。
实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。 - @RequestBody
处理HttpEntity传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据。
•GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。
•POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。 - 总结
•在GET请求中,不能使用@RequestBody。
•在POST请求,可以使用@RequestBody和@RequestParam,但是如果使用@RequestBody,对于参数转化的配置必须统一。
- @RequestParam
- 读取配置文件自定义配置
2.1 自定义配置的数值可以用@value读取
2.2 读取配置文件@Component @ConfigurationProperties @PropertySource@Value("${author.name}") private String author;
如果配置信息在外置配置文件里则可以通过读取配置文件的方式读取信息@Component @PropertySource(value = "classpath:author.properties")//指定外部配置文件的名字 @ConfigurationProperties(prefix = "author")//前缀,对应的是配置文件中的author
- @RequestHeader(),获取请求信息头,在参数用String接受
整合mybatis
- 添加依赖
<!-- 加载mybatis整合springboot --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!-- MySQL的jdbc驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- springboot 开发自动热部署 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <!-- alibaba的druid数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency>
- 让springboot编译mybatis文件
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources>
- 在application中配置信息
#指定mapper文件的位置 mybatis.mapper-locations=classpath:com/java/demo/dao/*.xml #指定bean的位置 mybatis.type-aliases-package=com.java.demo.bean #数据源 spring.datasource.username=root spring.datasource.password=passwd spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/sqldemo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone= Asia/Shanghai spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #查看sql语句日志 logging.level.com.java.demo.dao=debug
- 创建mapper和dao接口,dao接口类需要加上@Mapper注解,或者在main方法上加上@MapperScan注解,
4.1 书写xml
4.2 在dao方法上加上注解。 保存对象,获取数据库自增id @Options(useGeneratedKeys=true, keyProperty=“id”, keyColumn=“id”)<?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.java.demo.dao.StudentMapper"> <!--查询多条数据--> <select id="selectAllStudent" resultType="student"> SELECT id,name,age,score FROM t_student </select> </mapper>
@Select("SELECT * FROM user") @Results({ @Result(column = "create_time",property = "createTime") //javaType = java.util.Date.class }) List<User> getAll(); @Select("SELECT * FROM user WHERE id = #{id}") @Results({ @Result(column = "create_time",property = "createTime") }) User findById(Long id); @Update("UPDATE user SET name=#{name} WHERE id =#{id}") void update(User user); @Delete("DELETE FROM user WHERE id =#{userId}") void delete(Long userId);
- 创建service和实现类
- 开启事务
在入口类中使用注解 @EnableTransactionManagement 开启事务支持
在访问数据库的Service方法上添加注解 @Transactional(propagation=Propagation.REQUIRED,isolation=)(举例) 即可@SpringBootApplication @EnableTransactionManagement //开启事务支持 @MapperScan("com.java.demo.dao")//扫描mapper文件 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@Service @Transactional//开启事务 public class StudentServiceImpl implements StudentService{ @Autowired private StudentMapper studentMapper; @Override public List<Student> selectAllStudent() { System.out.println("测试"); return studentMapper.selectAllStudent(); } }
拦截器与过滤器
- 顺序:过滤器,拦截器,拦截器,过滤器
- filter简单理解:人—>检票员(filter)—> 景点
- SpringBoot启动默认加载的Filter
characterEncodingFilter hiddenHttpMethodFilter httpPutFormContentFilter requestContextFilter
- Filter优先级
Ordered.HIGHEST_PRECEDENCE
Ordered.LOWEST_PRECEDENCE
低位值意味着更高的优先级 Higher values are interpreted as lower priority
自定义Filter,避免和默认的Filter优先级一样,不然会冲突
注册Filter的bean FilterRegistrationBean
同模块里面有相关默认Filter
web->servlet->filter - 自定义Filter
1)使用Servlet3.0的注解进行配置
2)启动类里面增加 @ServletComponentScan,进行扫描
3)新建一个Filter类,implements Filter,并实现对应的接口
4) @WebFilter 标记一个类为filter,被spring进行扫描
urlPatterns:拦截规则,支持正则
5)控制chain.doFilter的方法的调用,来实现是否通过放行
不放行,web应用resp.sendRedirect("/index.html");
场景:权限控制、用户登录(非前端后端分离场景)等
- 自定义一个拦截器
1,1、
1.2、将拦截器加入到拦截器管理中public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("我的拦截器"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
@Configuration//表示该类会被spring容器创建 public class InterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { InterceptorRegistration r1 = registry.addInterceptor(new MyInterceptor()); //添加拦截请求 r1.addPathPatterns("/*"); //添加不拦截的请求 r1.excludePathPatterns("/login"); //上面跟下面的写法是一样的 //registry.addInterceptor(new PermissionInterceptor()).addPathPatterns("/*").excludePathPatterns("/login"); } }
- 配置过滤器方式一
然后再Springboot启动类上添加@ServletComponentScan@WebFilter(urlPatterns="/*") public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("进入filter过滤器"); chain.doFilter(request, response); } @Override public void destroy() { } }
@ServletComponentScan会扫描servlet相关的注解,比如@WebServlet、@WebFilter、@WebListener。 - 配置过滤器方式二
@Configuration public class FilterConfig { @Bean public FilterRegistrationBean myFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(new MyFilter()); registration.addUrlPatterns("/*"); return registration; } }
- servlet方式和filter差不多
4.1方式一@WebServlet("/myServlet") public class MyServlet extends HttpServlet { private static final long serialVersionUID = -4134217146900871026L; @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().print("hello word"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
方式二@SpringBootApplication @ServletComponentScan(basePackages="com.monkey1024.servlet") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@Configuration public class ServletConfig { @Bean public ServletRegistrationBean myServletRegistrationBean(){ ServletRegistrationBean registration = new ServletRegistrationBean(new MyServlet(), "/servlet/myServlet"); return registration; } }
restful
- 基本四个注解
@GetMapping()
@PostMapping()
@DeleteMapping()
@PutMapping()
actuator
- 介绍:在生产环境中,需要实时监控程序的可用性,出现问题之后我们需要快速定位,spring-boot 的 actuator 功能提供了很多监控所需的接口。actuator是spring boot提供的对应用系统的自省和监控的集成功能,可以对应用系统进行配置查看、健康检查、相关功能统计等;方便运维人员查看spring boot的运行状况。
- 使用:添加依赖和插件配置
<!--web依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--添加actuator依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!--spring boot admin依赖--> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-client</artifactId> </dependency>
#设置actuator监控端口 management.server.port=8081 #开启所有监控,默认只开启health和info management.endpoints.web.exposure.include=* #添加info信息 info.author=java.demo info.url=www.java.com
- 访问:actuator访问地址
http://localhost:8081/actuator/info
上传文件
使用MultipartFile
- 最直接:使用(@Requestparamram()MultipartFile file)获取文件,然后直接tranterto(“新的文件名”);
- getOriginalFilename():获取原文件名
- 设定文件最大值(在启动类中设置bean)
打包成jar包@Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); //单个文件最大 factory.setMaxFileSize("10240KB"); //KB,MB /// 设置总上传数据总大小 factory.setMaxRequestSize("1024000KB"); return factory.createMultipartConfig(); }
application.properties中增加下面配置,指定服务器的路径<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
web.images-path=/Users/jack/Desktop spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path}
热部署使用
- /META-INF/maven, /META-INF/resources, /resources, /static, /public, or /templates (默认不热部署)
- 指定文件不进行热部署 spring.devtools.restart.exclude=static/,public/
- 手工触发重启 spring.devtools.restart.trigger-file=trigger.txt 改代码不重启,通过一个文本去控制
- 注意点:生产环境不要开启这个功能,如果用java -jar启动,springBoot是不会进行热部署的
test使用
- 引入相关依赖
//使用<!--springboot程序测试依赖,如果是自动创建项目默认添加--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
@RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner @SpringBootTest(classes={XdclassApplication.class})//启动整个springboot工程 public class SpringBootTests { }
搭建出现的问题
- 接口参数接收问题,在springboot接受数据时,笔者忘了在接受数据的对象类型书写@RequestBody的注解,于是,在url请求成功发出后,controller成功相应了方法,但无法成功接受数据,于是对象数据直接全都为null。
MockMvc
- 测试MockMvc浏览器请求测试
@AutoConfigureMockMvc @SpringBootTest(classes={XdclassApplication.class}) @@RunWith(SpringRunner.class) public class SpringBootTests { MvcResult mvcResult =mockMvc.perform(MockMvcRequestBuilders.get("/test/home")).andExpect(MockMvcResultMatchers.status().isok()).andReturn(); System.out.printlnn(status); }
设置banner.txt改变初始显示数据
- 设置一个banner.txt,里面写上想要显示的内容
- 在properties里配置(吧banner.txt配置进去):spring.banner.location=banner.txt
springboot异常处理
- 捕捉Controller活动,监听。
如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody@ControllerAdvice
- 捕获全局异常,处理所有不可知的异常
注解在方法之上,方法解决相应的抛出异常
可放回modelandview或者Json数据@ExceptionHandler(value=Exception.class)
war包的springboot(直接改变就可以了)
- 为项目添加项目名称
xdclass_springboot - 修改启动类
public class XdclassApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(XdclassApplication.class); } public static void main(String[] args) throws Exception { SpringApplication.run(XdclassApplication.class, args); } }
freemarker模板引擎
- 引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
- 配置属性
# 是否开启thymeleaf缓存,本地为false,生产建议为true spring.freemarker.cache=false spring.freemarker.charset=UTF-8 spring.freemarker.allow-request-override=false spring.freemarker.check-template-location=true #类型 spring.freemarker.content-type=text/html spring.freemarker.expose-request-attributes=true spring.freemarker.expose-session-attributes=true #文件后缀 spring.freemarker.suffix=.ftl #路径 spring.freemarker.template-loader-path=classpath:/templates/
- 建立文件夹
1)src/main/resources/templates/fm/user/
2)建立一个index.ftl
3)user文件夹下面建立一个user.html
链接1
链接2
thymeleaf
- 引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
- 配置文件
#开发时关闭缓存,不然没法看到实时页面 spring.thymeleaf.cache=false spring.thymeleaf.mode=HTML5 #前缀 spring.thymeleaf.prefix=classpath:/templates/ #编码 spring.thymeleaf.encoding=UTF-8 #类型 spring.thymeleaf.content-type=text/html #名称的后缀 spring.thymeleaf.suffix=.html
- 设置静态文件夹
1)src/main/resources/templates/tl/
2)建立一个index.html
链接
redis
- 官网:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-redis
集群文档:https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#cluster - springboot整合redis相关依赖引入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
- application相关配置文件配置
#=========redis基础配置========= spring.redis.database=0 spring.redis.host=127.0.0.1 spring.redis.port=6390 # 连接超时时间 单位 ms(毫秒) spring.redis.timeout=3000 #=========redis线程池设置========= # 连接池中的最大空闲连接,默认值也是8。 spring.redis.pool.max-idle=200 #连接池中的最小空闲连接,默认值也是0。 spring.redis.pool.min-idle=200 # 如果赋值为-1,则表示不限制;pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。 spring.redis.pool.max-active=2000 # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时 spring.redis.pool.max-wait=1000
- 注入模板
@Autowired
private StirngRedisTemplate strTplRedis
类型String,List,Hash,Set,ZSet
对应的方法分别是opsForValue()、opsForList()、opsForHash()、opsForSet()、opsForZSet() - 常用客户端 https://redisdesktop.com/download
整合定时任务和异步任务类
- jdk原生timer类(时间延后问题)
- Quartz框架
- springboot内置注解
1)启动类里面 @EnableScheduling开启定时任务,自动扫描
2)定时任务业务类 加注解 @Component被容器扫描
3)定时执行的方法加上注解 @Scheduled(fixedRate=2000) 定期执行一次 - cron 定时任务表达式 @Scheduled(cron="*/1 * * * * *") 表示每秒
1)crontab 工具 https://tool.lu/crontab/
2)fixedRate: 定时多久执行一次(上一次开始执行时间点后xx秒再次执行;)
3)fixedDelay: 上一次执行结束时间点后xx秒再次执行
4)fixedDelayString: 字符串形式,可以通过配置文件指定 - 异步任务
- @EnableAsync注解开启功能,自动扫描
- 定义异步任务类并使用@Component标记组件被容器扫描,异步方法加上@Async(可以加在类上)
注意点:
1)要把异步任务封装到类里面,不能直接写到Controller
2)增加Future 返回结果 AsyncResult(“task执行完成”);
3)如果需要拿到结果 需要判断全部的 task.isDone()@Autowired AsyncTask at =new AsyncTask(); public void demofunction(){ at.task1(); Future<String> result2=at.task2(); if(task2.isDone()) { //result2完成的操作 } }
@Async public void task1() throws InterruptedException { Tread.sleep(1000L); } @Async public Future<String> task2() throws InterruptedException { Tread.sleep(1000L); return AsyncResult<String>("task执行完成"); }
- 通过注入方式,注入到controller里面,如果测试前后区别则改为同步则把Async注释掉
logback框架整合
- Log4j日志转换为logback在线工具(支持log4j.properties转换为logback.xml,不支持 log4j.xml转换为logback.xml)
- logback官网
组件案例<!-- xml--> <configuration> 子节点 <appender></appender> <logger></logger> <root></root>(要加在最后)
SpringBoot2.x整合elasticsearch5.6.x搭建
- Spring Data Elasticsearch文档地址
- 版本说明:SpringBoot整合elasticsearch
- https://docs.spring.io/spring-data/elasticsearch/docs/3.2.0.RC1/reference/html/#reference
- 依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
- 简单实现
- 创建pojo:@Document(indexName = “blog”, type = “article”)在pojo上注解,并且实现Servialize接口
- 书写接口并实现ElasticSearchRepository同时加上注解@Component(@Document(indexName = “blog”, type = "article"其他属性),)
- 配置文件
ELASTICSEARCH (ElasticsearchProperties) spring.data.elasticsearch.cluster-name=elasticsearch # Elasticsearch cluster name. spring.data.elasticsearch.cluster-nodes=localhost:9300 # Comma-separated list of cluster node addresses. spring.data.elasticsearch.repositories.enabled=true # Whether to enable Elasticsearch repositories.
- QueryBuilder使用
//单个匹配,搜索name为jack的文档
QueryBuilder queryBuilder = QueryBuilders.matchQuery(“title”, “搜”); - 查看es数据
查看索引信息:http://localhost:9200/_cat/indices?v
查看某个索引库结构:http://localhost:9200/blog
查看某个对象:http://localhost:9200/blog/article/1
java消息队列(RockketMQ、ActiveMQ)
一. ActiveMQ
- 下载地址
- 打开:如果我们是32位的机器,就双击win32目录下的activemq.bat,如果是64位机器,则双击win64目录下的activemq.bat
bin目录里面启动 选择对应的系统版本和位数,activeMQ start 启动(指电脑的版本) - 默认的访问路径:http://127.0.0.1:8161/ 账号密码都为admin
- 结合springboot:
4.1 官网地址
4.2 导入依赖
4.3 application.properties配置<!-- 整合消息队列ActiveMQ --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> <!-- 如果配置线程池则加入 --> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-pool</artifactId> </dependency>
4.4 springboot启动类 @EnableJms,开启支持jmsspring.activemq.broker-url=tcp://127.0.0.1:61616 #集群配置 #spring.activemq.broker-url=failover:(tcp://localhost:61616,tcp://localhost:61617) spring.activemq.user=admin spring.activemq.password=admin #下列配置要增加依赖 spring.activemq.pool.enabled=true spring.activemq.pool.max-connections=100 #配置信息支持模型开启后不支持点对点而支持多订阅 #default point to point spring.jms.pub-sub-domain=true
通过jmstemplate来发送消息
4.5 消费者 @JmsListener(destination = “order.queue”) 实时监听队列,可以加在方法上。
4.6 如果要都支持需要多写工厂
然后再注解里添加containerFactory=“jmsListenerContainerTopic”@Bean public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ConnectionFactory activeMQConnectionFactory) { DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory(); bean.setPubSubDomain(true); bean.setConnectionFactory(activeMQConnectionFactory); return bean; }
二. RocketMQ
- 下载
- 经入bin后 : nohup sh mqnamesrv &
然后启动broker :nohup sh mqbroker -n 127.0.0.1:9876 & - 关闭
sh mqshutdown namesrv
sh mqshutdown broker - RocketMQ的可视化
https://github.com/apache/rocketmq-externals
编译打包 mvn clean package -Dmaven.test.skip=true
target目录 通过java -jar的方式运行 - 无法连接获取broker信息(这个springboot的application.properties)
1)修改配置文件,名称路由地址为 namesrvAddr,例如我本机为
2)src/main/resources/application.properties
rocketmq.config.namesrvAddr=192.168.0.101:9876
默认端口为8080,注意防火墙和端口开放 - 实战
6.1 导入依赖
6.2application.properties加入配置文件<dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-client</artifactId> <version>${rocketmq.version}</version> </dependency> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-common</artifactId> <version>${rocketmq.version}</version> </dependency>
6.3生产者# 消费者的组名 apache.rocketmq.consumer.PushConsumer=orderConsumer # 生产者的组名 apache.rocketmq.producer.producerGroup=Producer # NameServer地址 apache.rocketmq.namesrvAddr=127.0.0.1:9876
6.4 生产者/** * 生产者的组名 */ @Value("${apache.rocketmq.producer.producerGroup}") private String producerGroup; /** * NameServer 地址 */ @Value("${apache.rocketmq.namesrvAddr}") private String namesrvAddr; private DefaultMQProducer producer ; public DefaultMQProducer getProducer(){ return this.producer; } @PostConstruct public void defaultMQProducer() { //生产者的组名 producer = new DefaultMQProducer(producerGroup); //指定NameServer地址,多个地址以 ; 隔开 //如 producer.setNamesrvAddr("192.168.100.141:9876;192.168.100.142:9876;192.168.100.149:9876"); producer.setNamesrvAddr(namesrvAddr); producer.setVipChannelEnabled(false); try { /** * Producer对象在使用之前必须要调用start初始化,只能初始化一次 */ producer.start(); } catch (Exception e) { e.printStackTrace(); } // producer.shutdown(); 一般在应用上下文,关闭的时候进行关闭,用上下文监听器 }
解决:多网卡问题处理1、Caused by: org.apache.rocketmq.remoting.exception.RemotingConnectException: connect to <172.17.42.1:10911> failed 2、com.alibaba.rocketmq.client.exception.MQClientException: Send [1] times, still failed, cost [1647]ms, Topic: TopicTest1, BrokersSent: [broker-a, null, null] 3、org.apache.rocketmq.client.exception.MQClientException: Send [3] times, still failed, cost [497]ms, Topic: TopicTest, BrokersSent: [chenyaowudeMacBook-Air.local, chenyaowudeMacBook-Air.local, chenyaowudeMacBook-Air.local]
6.5 DESC:1、设置producer: producer.setVipChannelEnabled(false); 2、编辑ROCKETMQ 配置文件:broker.conf(下列ip为自己的ip) namesrvAddr = 192.168.0.101:9876 brokerIP1 = 192.168.0.101
解决:修改启动脚本runbroker.sh,在里面增加一句话即可:service not available now, maybe disk full, CL:
JAVA_OPT="${JAVA_OPT} -Drocketmq.broker.diskSpaceWarningLevelRatio=0.98" (磁盘保护的百分比设置成98%,只有磁盘空间使用率达到98%时才拒绝接收producer消息)
- 常见问题处理:
https://blog.csdn.net/sqzhao/article/details/54834761
https://blog.csdn.net/mayifan0/article/details/67633729
https://blog.csdn.net/a906423355/article/details/78192828
响应式编程
官网:SpingBoot2底层是用spring5,开始支持响应式编程,Spring又是基于Reactor试下响应式
资料:
2.1、reactive-streams学习资料:
2.2、web-flux相关资料:webflx介绍
3.1、Spring WebFlux是Spring Framework 5.0中引入的新的反应式Web框架3.2、Flux和Mono User List
简单业务而言:和其他普通对象差别不大,复杂请求业务,就可以提升性能
通俗理解:
Mono 表示的是包含 0 或者 1 个元素的异步序列
mono->单一对象 User redis->用户ID-》唯一的用户Mono
Flux 表示的是包含 0 到 N 个元素的异步序列
flux->数组列表对象 List redis->男性用户->Flux
Flux 和 Mono 之间可以进行转换
与Spring MVC不同,它不需要Servlet API,完全异步和非阻塞,并 通过Reactor项目实现Reactive Streams规范。RxJava3.3、Spring WebFlux有两种风格:基于功能和基于注解的。基于注解非常接近Spring MVC模型,如以下示例所示:
第一种:@RestController @RequestMapping(“/ users”) public class MyRestController { @GetMapping(“/ {user}”) public Mono <User> getUser( @PathVariable Long user){ // ... } @GetMapping(“/ {user} / customers”) public Flux <Customer> getUserCustomers( @PathVariable Long user){ // ... } @DeleteMapping(“/ {user}”) public Mono <User> deleteUser( @PathVariable Long user){ // ... } }
第二种: 路由配置与请求的实际处理分开
@Configuration public class RoutingConfiguration { @Bean public RouterFunction <ServerResponse> monoRouterFunction(UserHandler userHandler){ return route(GET( “/ {user}”).and(accept(APPLICATION_JSON)),userHandler :: getUser) .andRoute(GET(“/ {user} / customers”).and(accept(APPLICATION_JSON)),userHandler :: getUserCustomers) .andRoute(DELETE(“/ {user}”).and(accept(APPLICATION_JSON)),userHandler :: deleteUser); } } @Component public class UserHandler { 公共 Mono <ServerResponse> getUser(ServerRequest请求){ // ... } public Mono <ServerResponse> getUserCustomers(ServerRequest request){ // ... } 公共 Mono <ServerResponse> deleteUser(ServerRequest请求){ // ... } }
3.4、Spring WebFlux应用程序不严格依赖于Servlet API,因此它们不能作为war文件部署,也不能使用src/main/webapp目录
3.5、可以整合多个模板引擎
除了REST Web服务外,您还可以使用Spring WebFlux提供动态HTML内容。Spring WebFlux支持各种模板技术,包括Thymeleaf,FreeMarker应用
4.1、WebFlux中,请求和响应不再是WebMVC中的ServletRequest和ServletResponse,而是ServerRequest和ServerResponse4.2、加入依赖,如果同时存在spring-boot-starter-web,则会优先用spring-boot-starter-web
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
4.3、测试
localhost:8080/api/v1/user/test
启动方式默认是Netty,8080端口4.4、参考:https://spring.io/blog/2016/04/19/understanding-reactive-types
webClient客户端
5.1、反应式客户端
官网地址:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-webclient使用SSH:修改Mapping的produces属性为"text/event-stream;charset=UTF-8"
var source=new EventSource("controller"); source.onmessage=function(event) { document.getElementById("result").innerHTML+=event.data + "<br />"; //dosomething }; source.onopen=function(event) { //dosomething }; source.ononerror=function(event) { //dosomething };
监控
- 引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
- application
#设置actuator监控端口 management.server.port=8081 #开启所有监控,默认只开启health和info management.endpoints.web.exposure.include=* #添加info信息 info.author=monkey1024 info.url=www.monkey1024.com