在这里,我们将给大家分享关于如何在Spring-boot中轻松配置Jetty?的知识,让您更了解springbootjetty配置的本质,同时也会涉及到如何更有效地SpringBoot–Jetty配置
在这里,我们将给大家分享关于如何在Spring-boot中轻松配置Jetty?的知识,让您更了解springboot jetty配置的本质,同时也会涉及到如何更有效地Spring Boot – Jetty 配置、Spring Boot – Jetty配置、在Jetty上使用Spring Boot和Spring MVC Rest API配置Spring安全性、在SpringBoot中,如何使用Netty实现远程调用方法总结的内容。
本文目录一览:- 如何在Spring-boot中轻松配置Jetty?(springboot jetty配置)
- Spring Boot – Jetty 配置
- Spring Boot – Jetty配置
- 在Jetty上使用Spring Boot和Spring MVC Rest API配置Spring安全性
- 在SpringBoot中,如何使用Netty实现远程调用方法总结
如何在Spring-boot中轻松配置Jetty?(springboot jetty配置)
通过遵循本教程,我可以使用以下依赖项启动Jetty的spring-boot。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency>
但是,如何配置Jetty服务器,例如:
- 服务器线程(队列线程池)
- 服务器连接器
- Https配置。
- Jetty中所有可用的配置…?
有一个简单的方法可以做
- application.yml?
- 配置类?
任何例子将不胜感激。
非常感谢!!
答案1
小编典典Servlet容器有一些常规扩展点,还有一些将Jetty
API调用插入其中的选项,因此,我认为可以满足您的所有需求。一般建议可以在文档中找到。Jetty尚未引起足够的重视,因此声明式配置可能没有与Tomcat相同的选项,并且可以肯定的是它不会被使用太多。如果您想帮助改变这一点,欢迎提供帮助。
Spring Boot – Jetty 配置
前言
默认情况下,Spring Boot 会使用内置的 tomcat 容器去运行应用程序,但偶尔我们也会考虑使用 Jetty 去替代 Tomcat;
对于 Tomcat 和 Jetty,Spring Boot 分别提供了对应的 starter,以便尽可能的简化我们的开发过程;
当我们想使用 Jetty 的时候,可以参考以下步骤来使用。
添加 spring-boot-starter-jetty 依赖
我们需要更新 pom.xml
文件,添加 spring-boot-starter-jetty
依赖,同时我们需要排除 spring-boot-starter-web
默认的 spring-boot-starter-tomcat
依赖,如下所示:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
如果我们的工程是使用 Gradle 构建的话,可以使用以下方式达到同样的效果:
configurations {
compile.exclude module: "spring-boot-starter-tomcat"
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:2.0.0.BUILD-SNAPSHOT")
compile("org.springframework.boot:spring-boot-starter-jetty:2.0.0.BUILD-SNAPSHOT")
}
重启完成之后,再次查看控制台打印的日志信息,Jetty started,以此可以确定替换 jetty 成功
Spring Boot – Jetty配置
前言
默认情况下,Spring Boot会使用内置的tomcat容器去运行应用程序,但偶尔我们也会考虑使用Jetty去替代Tomcat; 对于Tomcat和Jetty,Spring Boot分别提供了对应的starter,以便尽可能的简化我们的开发过程; 当我们想使用Jetty的时候,可以参考以下步骤来使用。
添加spring-boot-starter-jetty依赖
我们需要更新pom.xml
文件,添加spring-boot-starter-jetty
依赖,同时我们需要排除spring-boot-starter-web
默认的spring-boot-starter-tomcat
依赖,如下所示:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
如果我们的工程是使用Gradle构建的话,可以使用以下方式达到同样的效果:
configurations {
compile.exclude module: "spring-boot-starter-tomcat"
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:2.0.0.BUILD-SNAPSHOT")
compile("org.springframework.boot:spring-boot-starter-jetty:2.0.0.BUILD-SNAPSHOT")
}
配置Jetty参数
我们可以在application.properties配置文件里配置相关参数,去覆盖Jetty默认使用的运行参数: application.properties
server.port=8080
server.servlet.context-path=/home
####Jetty specific properties########
server.jetty.acceptors= # Number of acceptor threads to use.
server.jetty.max-http-post-size=0 # Maximum size in bytes of the HTTP post or put content.
server.jetty.selectors= # Number of selector threads to use.
同样,我们可以通过JettyEmbeddedServletContainerFactory
bean以编程的方式去配置这些参数
@Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() {
JettyEmbeddedServletContainerFactory jettyContainer =
new JettyEmbeddedServletContainerFactory();
jettyContainer.setPort(9000);
jettyContainer.setContextPath("/home");
return jettyContainer;
}
Spring boot 2.0.0.RELEASE版本之后的更新
以上代码针对的是Spring Boot Snapshot版本,在Spring boot 2.0.0.RELEASE版本之后,我们应该使用 ConfigurableServletWebServerFactory
和 JettyServletWebServerFactory
类去配置Jetty参数: 创建ConfigurableServletWebServerFactory
Bean
@Bean
public ConfigurableServletWebServerFactory webServerFactory()
{
JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
factory.setPort(9000);
factory.setContextPath("/myapp");
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"));
return factory;
}
原文文链
Site4J
在Jetty上使用Spring Boot和Spring MVC Rest API配置Spring安全性
我目前正在使用Jetty上托管的spring boot和spring mvc制作Rest
API。此时一切正常。现在我想添加spring安全性,但是它抛出一个异常:
FAILED org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$InitializerListener@36895c35: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ''springSecurityFilterChain'' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ''org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration'': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration.setGlobalAuthenticationConfigurers(java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ''org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration'': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.List org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration.dependencies; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ''securityProperties'': Could not bind properties; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property ''bean'' of bean class [org.springframework.boot.autoconfigure.security.SecurityProperties]: Bean property ''bean'' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
所以这是我的主要课程:
@Configuration@ComponentScan@EnableAutoConfiguration@PropertySource({"classpath:configuration.properties"})@Import({ApplicationConfig.class, SecurityConfig.class})public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Autowired private Environment environment; public Environment getEnvironment() { return environment; } public void setEnvironment(Environment environment) { this.environment = environment; }}
这是我的应用程序配置
@EnableWebMvc@Configuration@EnableTransactionManagementpublic class ApplicationConfig { @Autowired private Environment environment; public Environment getEnvironment() { return environment; } public void setEnvironment(Environment environment) { this.environment = environment; } @Bean(name = "dataSource") public DriverManagerDataSource getDataSource() { DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(); driverManagerDataSource.setDriverClassName(this.getEnvironment().getProperty("database.driver")); driverManagerDataSource.setUrl(this.getEnvironment().getProperty("database.url")); driverManagerDataSource.setUsername(this.getEnvironment().getProperty("database.username")); driverManagerDataSource.setPassword(this.getEnvironment().getProperty("database.password")); return driverManagerDataSource; } @Bean(name = "sessionFactory") public SessionFactory getSessionFactory() { LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(this.getDataSource()); builder.scanPackages("apt.model").addProperties(this.getHibernateProperties()); return builder.buildSessionFactory(); } private Properties getHibernateProperties() { Properties prop = new Properties(); prop.put("hibernate.format_sql", this.getEnvironment().getProperty("database.verbose")); prop.put("hibernate.show_sql", this.getEnvironment().getProperty("database.verbose")); prop.put("hibernate.dialect", this.getEnvironment().getProperty("database.dialect")); prop.put("hbm2ddl.auto", this.getEnvironment().getProperty("database.hbm2ddl")); prop.put("c3p0.min_size", "5"); prop.put("c3p0.max_size", "50"); prop.put("c3p0.timeout", "300"); prop.put("c3p0.max_statements", "50"); prop.put("c3p0.idle_test_period", "3000"); return prop; } @Bean(name = "txManager") public HibernateTransactionManager getTransactionManager() { return new HibernateTransactionManager(this.getSessionFactory()); }}
这是安全配置
@Configuration@EnableWebSecurity@EnableAutoConfigurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AccountService accountService; @Autowired private AuthenticationService authenticationService; public AccountService getAccountService() { return accountService; } public void setAccountService(AccountService accountService) { this.accountService = accountService; } public AuthenticationService getAuthenticationService() { return authenticationService; } public void setAuthenticationService(AuthenticationService authenticationService) { this.authenticationService = authenticationService; } @Override public void setAuthenticationConfiguration(AuthenticationConfiguration authenticationConfiguration) { super.setAuthenticationConfiguration(authenticationConfiguration); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/**").permitAll().anyRequest().authenticated(); http.formLogin().loginPage("/authentication/login").permitAll().and().logout().permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(this.getAuthenticationService()).passwordEncoder(this.getPasswordEncoder()); } @Bean(name = "passwordEncoder") public PasswordEncoder getPasswordEncoder() { return new BCryptPasswordEncoder(); }}
你知道它从哪里来吗?
答案1
小编典典听起来好像您已经定义了一个名为属性security.bean
,这会导致Spring
Boot的绑定错误org.springframework.boot.autoconfigure.security.SecurityProperties
。
发生这种情况是因为SecurityProperties
带有注释,@ConfigurationProperties(name = "security",ignoreUnknownFields = false)
并且不包含名为的属性bean
。
简而言之,您不应具有任何以引用开头security.
未列出的属性。
在SpringBoot中,如何使用Netty实现远程调用方法总结
我们在进行网络连接的时候,建立套接字连接是一个非常消耗性能的事情,特别是在分布式的情况下,用线程池去保持多个客户端连接,是一种非常消耗线程的行为.那么我们该通过什么技术去解决上述的问题呢,那么就不得不提一个网络连接的利器――Netty,需要的朋友可以参考下
Netty
Netty是一个NIO客户端服务器框架:
它可快速轻松地开发网络应用程序,例如协议服务器和客户端。
它极大地简化和简化了网络编程,例如TCP和UDP套接字服务器。
NIO是一种非阻塞IO ,它具有以下的特点
单线程可以连接多个客户端。
选择器可以实现单线程管理多个Channel,新建的通道都要向选择器注册。
一个SelectionKey键表示了一个特定的通道对象和一个特定的选择器对象之间的注册关系。
selector进行select()操作可能会产生阻塞,但是可以设置阻塞时间,并且可以用wakeup()唤醒selector,所以NIO是非阻塞IO。
Netty模型selector模式
它相对普通NIO的在性能上有了提升,采用了:
NIO采用多线程的方式可以同时使用多个selector
通过绑定多个端口的方式,使得一个selector可以同时注册多个ServerSocketServer
单个线程下只能有一个selector,用来实现Channel的匹配及复用
半包问题
TCP/IP在发送消息的时候,可能会拆包,这就导致接收端无法知道什么时候收到的数据是一个完整的数据。在传统的BIO中在读取不到数据时会发生阻塞,但是NIO不会。为了解决NIO的半包问题,Netty在Selector模型的基础上,提出了reactor模式,从而解决客户端请求在服务端不完整的问题。
netty模型reactor模式
在selector的基础上解决了半包问题。
上图,简单地可以描述为"boss接活,让work干":manReactor用来接收请求(会与客户端进行握手验证),而subReactor用来处理请求(不与客户端直接连接)。
SpringBoot使用Netty实现远程调用
maven依赖
org.projectlomboklombok1.18.2trueio.nettynetty-all4.1.17.Final
服务端部分
NettyServer.java:服务启动监听器
@Slf4j public class NettyServer { public void start() { InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8082); //new 一个主线程组 EventLoopGroup bossGroup = new NioEventLoopGroup(1); //new 一个工作线程组 EventLoopGroup workGroup = new NioEventLoopGroup(200); ServerBootstrap bootstrap = new ServerBootstrap() .group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .childHandler(new ServerChannelInitializer()) .localAddress(socketAddress) //设置队列大小 .option(ChannelOption.so_BACKLOG, 1024) // 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文 .childOption(ChannelOption.so_KEEPALIVE, true); //绑定端口,开始接收进来的连接 try { ChannelFuture future = bootstrap.bind(socketAddress).sync(); log.info("服务器启动开始监听端口: {}", socketAddress.getPort()); future.channel().closeFuture().sync(); } catch (InterruptedException e) { log.error("服务器开启失败", e); } finally { //关闭主线程组 bossGroup.shutdownGracefully(); //关闭工作线程组 workGroup.shutdownGracefully(); } } }
ServerChannelInitializer.java:netty服务初始化器
/** * netty服务初始化器 **/ public class ServerChannelInitializer extends ChannelInitializer { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { //添加编解码 socketChannel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8)); socketChannel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); socketChannel.pipeline().addLast(new NettyServerHandler()); } }
NettyServerHandler.java:netty服务端处理器
/** * netty服务端处理器 **/ @Slf4j public class NettyServerHandler extends ChannelInboundHandlerAdapter { /** * 客户端连接会触发 */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { log.info("Channel active......"); } /** * 客户端发消息会触发 */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { log.info("服务器收到消息: {}", msg.toString()); ctx.write("你也好哦"); ctx.flush(); } /** * 发生异常触发 */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printstacktrace(); ctx.close(); } }
RpcServerApp.java:SpringBoot启动类
/** * 启动类 * */ @Slf4j @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class RpcServerApp extends SpringBootServletinitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(RpcServerApp.class); } /** * 项目的启动方法 * * @param args */ public static void main(String[] args) { SpringApplication.run(RpcServerApp.class, args); //开启Netty服务 NettyServer nettyServer =new NettyServer (); nettyServer.start(); log.info("======服务已经启动========"); } }
客户端部分
NettyClientUtil.java:NettyClient工具类
/** * Netty客户端 **/ @Slf4j public class NettyClientUtil { public static ResponseResult helloNetty(String msg) { NettyClientHandler nettyClientHandler = new NettyClientHandler(); EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap() .group(group) //该参数的作用就是禁止使用Nagle算法,使用于小数据即时传输 .option(ChannelOption.TCP_NODELAY, true) .channel(NioSocketChannel.class) .handler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast("decoder", new StringDecoder()); socketChannel.pipeline().addLast("encoder", new StringEncoder()); socketChannel.pipeline().addLast(nettyClientHandler); } }); try { ChannelFuture future = bootstrap.connect("127.0.0.1", 8082).sync(); log.info("客户端发送成功...."); //发送消息 future.channel().writeAndFlush(msg); // 等待连接被关闭 future.channel().closeFuture().sync(); return nettyClientHandler.getResponseResult(); } catch (Exception e) { log.error("客户端Netty失败", e); throw new BusinessException(CouponTypeEnum.OPERATE_ERROR); } finally { //以一种优雅的方式进行线程退出 group.shutdownGracefully(); } } }
NettyClientHandler.java:客户端处理器
/** * 客户端处理器 **/ @Slf4j @Setter @Getter public class NettyClientHandler extends ChannelInboundHandlerAdapter { private ResponseResult responseResult; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { log.info("客户端Active ....."); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { log.info("客户端收到消息: {}", msg.toString()); this.responseResult = ResponseResult.success(msg.toString(), CouponTypeEnum.OPERATE_SUCCESS.getCouponTypeDesc()); ctx.close(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printstacktrace(); ctx.close(); } }
验证
测试接口
@RestController @Slf4j public class UserController { @PostMapping("/helloNetty") @MethodLogPrint public ResponseResult helloNetty(@RequestParam String msg) { return NettyClientUtil.helloNetty(msg); } }
访问测试接口
服务端打印信息
客户端打印信息
到此这篇关于在SpringBoot中,如何使用Netty实现远程调用方法总结的文章就介绍到这了,更多相关Netty实现远程调用内容请搜索小编以前的文章或继续浏览下面的相关文章希望大家以后多多支持小编!
今天关于如何在Spring-boot中轻松配置Jetty?和springboot jetty配置的介绍到此结束,谢谢您的阅读,有关Spring Boot – Jetty 配置、Spring Boot – Jetty配置、在Jetty上使用Spring Boot和Spring MVC Rest API配置Spring安全性、在SpringBoot中,如何使用Netty实现远程调用方法总结等更多相关知识的信息可以在本站进行查询。
本文标签: