SpringBoot第二天

目錄

1.Web開發

1.1簡介

1.2SpringBoot對靜態資源的映射規則

1.3模板引擎

1.3.1引入thymeleaf;

1.3.2Thymeleaf語法

1.3.2.1標準表達式語法

????????1.變量表達式

1.3.2.2表達式支持的語法

1.3.2.3常用的thymeleaf標簽

1.4Springboot整合springmvc

1.4.1Springmvc的自動解管理

1.4.1.1中央轉發器

1.4.1.2控制器

1.4.1.3視圖解析器自動管理

1.4.1.4靜態資源訪問

1.4.1.5消息轉換和格式化

1.4.1.6歡迎頁面的自動配置

1.4.2Springboot擴展springmvc?

1.4.2.1在容器中注冊視圖控制器(請求轉發)

1.4.2.2注冊格式化器

1.4.2.3消息轉換器擴展fastjson

1.4.2.4攔截器注冊

1.5配置嵌入式服務器

1.5.1如何定制和修改Servlet容器的相關配置;

1.5.2注冊Servlet三大組件【Servlet、Filter、Listener】

1.6使用外置的Servlet容器


1.Web開發

1.1簡介

使用SpringBoot
1)、創建SpringBoot應用,選中我們需要的模塊;
2)、SpringBoot已經默認將這些場景配置好了,只需要在配置文件中指定少量配置就可以運行起來
3)、自己編寫業務代碼;

自動配置原理?
這個場景SpringBoot幫我們配置了什么?能不能修改?能修改哪些配置?能不能擴展?xxx

1.2SpringBoot對靜態資源的映射規則

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
//可以設置和靜態資源有關的參數,緩存時間等
WebMvcAuotConfiguration:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {if (!this.resourceProperties.isAddMappings()) {logger.debug("Default resource handling disabled");return;} 
Integer cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) {customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META‐INF/resources/webjars/").setCachePeriod(cachePeriod));
} 
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
//靜態資源文件夾映射
if (!registry.hasMappingForPattern(staticPathPattern)) {customizeResourceHandlerRegistration(registry.
addResourceHandler(staticPathPattern).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod));
}
} /
/配置歡迎頁映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) {return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
}
//配置喜歡的圖標
@Configuration
@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
public static class FaviconConfiguration {private final ResourceProperties resourceProperties;public FaviconConfiguration(ResourceProperties resourceProperties) {this.resourceProperties = resourceProperties;
}@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);//所有 **/favicon.icomapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
faviconRequestHandler());
return mapping;
} 
@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();requestHandler.setLocations(this.resourceProperties.getFaviconLocations());return requestHandler;}
}

1)、所有?/webjars/** ,都去?classpath:/META-INF/resources/webjars/ 找資源;

webjars:以jar包的方式引入靜態資源;WebJars - Web Libraries in Jars

?

????????localhost:8080/webjars/jquery/3.3.1/jquery.js?

<!‐‐引入jquery‐webjar‐‐>在訪問的時候只需要寫webjars下面資源的名稱即可
<dependency><groupId>org.webjars</groupId><artifactId>jquery</artifactId><version>3.3.1</version>
</dependency>

2)、"/**" 訪問當前項目的任何資源,都去(靜態資源的文件夾)找映射

"classpath:/META‐INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":當前項目的根路徑

localhost:8080/abc === 去靜態資源文件夾里面找abc

3)、歡迎頁;?靜態資源文件夾下的所有index.html頁面;被"/**"映射;

localhost:8080/ index頁面

1.3模板引擎

JSPVelocityFreemarkerThymeleaf

SpringBoot推薦的Thymeleaf

語法更簡單,功能更強大;

1.3.1引入thymeleaf

????????在pom.xml中引入

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

????????從spring父文件中能看到Springboot2.0.1所使用的thymeleaf版本是3.0.9

????????springBoot啟動的時候會自動配置

org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration

????????從ThymeleafAutoConfiguration的源代碼中我們可以得知ThymeleafProperties中配置了Thymeleaf的規則

public class ThymeleafProperties {private static final Charset DEFAULT_ENCODING;public static final String DEFAULT_PREFIX = "classpath:/templates/";public static final String DEFAULT_SUFFIX = ".html";private boolean checkTemplate = true;private boolean checkTemplateLocation = true;private String prefix = "classpath:/templates/";private String suffix = ".html";private String mode = "HTML";private Charset encoding;private boolean cache;
}

我們使用html作為模板,而且默認的前綴是放在classpath:/templates/下,后綴是.html

當然這些屬性我們都可以通過application.properties來修改我們采用默認即可。

示例

  1. templates下創建一個success.html
  2. html中引入thymeleaf的命名空間
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. 創建一個Controller提供一個訪問的方法
    @RequestMapping("/success")
    public String hello(Model model){model.addAttribute("hello","<h1>zhangsan</h1>");return "success";
    }
  4. thymeleaf模板中取值
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head><title>Title</title>
    </head>
    <body>
    <div  th:text="${hello}"> </div>
    </body>
    </html>

1.3.2Thymeleaf語法

1.3.2.1標準表達式語法
????????1.變量表達式

變量表達式即OGNL表達式或Spring EL表達式(Spring術語中也叫model attributes)。如下所示:?${session.user.name}

它們將以HTML標簽的一個屬性來表示:

<span th:text="${book.author.name}"> 

????????2.選擇(星號)表達式

????????選擇表達式很像變量表達式,不過它們用一個預先選擇的對象來代替上下文變量容器(map)來執行,如下:?*{customer.name}

????????被指定的objectth:object屬性定義:

<div th:object="${book}"> ... <span th:text="*{title}">...</span> ... 
</div>

????????3.文字國際化表達式

????????文字國際化表達式允許我們從一個外部文件獲取區域文字信息(.properties),用Key索引Value,還可以提供一組參數(可選).

#{main.title}

????????4.URL表達式

URL表達式指的是把一個有用的上下文或回話信息添加到URL,這個過程經常被叫做URL重寫。不需要指定項目名字
@{/order/list}?

URL還可以設置參數:

@{/order/details(id=${orderId})}?

讓我們看這些表達式:

<form th:action="@{/createOrder}"> 
<a href="main.html" rel="external nofollow" th:href="@{/main}" rel="external n
1.3.2.2表達式支持的語法

字面(Literals)

  • 文本文字(Text literals): 'one text', 'Another one!',…
  • 數字文本(Number literals): 0, 34, 3.0, 12.3,…
  • 布爾文本(Boolean literals): true, false
  • 空(Null literal): null
  • 文字標記(Literal tokens): one, sometext, main,…

文本操作(Text operations)

  • 字符串連接(String concatenation): +
  • 文本替換(Literal substitutions): |The name is ${name}|

算術運算(Arithmetic operations)

  • 二元運算符(Binary operators): +, -, *, /, %
  • 減號(單目運算符)Minus sign (unary operator): -

布爾操作(Boolean operations)

  • 二元運算符(Binary operators):and, or
  • 布爾否定(一元運算符)Boolean negation (unary operator):!, not

比較和等價(Comparisons and equality)

  • 比較(Comparators): >, <, >=, <= (gt, lt, ge, le)
  • 等值運算符(Equality operators):==, != (eq, ne)

條件運算符(Conditional operators)

If-then: (if) ? (then)

If-then-else: (if) ? (then) : (else)

Default: (value) ?: (defaultvalue)

示例代碼

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

1.3.2.3常用的thymeleaf標簽

關鍵字

功能介紹

案例

th:id

替換id

<input th:id="'xxx' + ${collect.id}"/>

th:text

文本替換

<p th:text="${collect.description}">description</p>

th:utext

支持html的文本替換

<p th:utext="${htmlcontent}">conten</p>

th:object

替換對象

<div th:object="${session.user}">

th:value

屬性賦值

<input th:value="${user.name}" />

th:onclick

點擊事件

th:οnclick="'getCollect()'"

th:each

屬性賦值

tr th:each="user,userStat:${users}">

th:if

判斷條件

<a th:if="${userId == collect.userId}" >

th:unless

和th:if判斷相反

<a th:href="@{/login}" rel="external nofollow" rel="external nofollow" rel="external nofollow" th:unless=${session.user != null}>Login</a>

th:href

鏈接地址

<a th:href="@{/login}" rel="external nofollow" rel="external nofollow" rel="external nofollow" th:unless=${session.user != null}>Login</a> />

th:switch

多路選擇 配合th:case 使用

<div th:switch="${user.role}">

th:case

th:switch的一個分支

<p th:case="'admin'">User is an administrator</p>

th:fragment

布局標簽,定義一個代碼片段,方便其它地方引用

<div th:fragment="alert">

th:include

布局標簽,替換內容到引入的文件

<head th:include="layout :: htmlhead" th:with="title='xx'"></head> />

th:replace

布局標簽,替換整個標簽到引入的文件

<div th:replace="fragments/header :: title"></div>

th:selected

selected選擇框 選中

th:selected="(${xxx.id} == ${configObj.dd})"

th:src

圖片類地址引入

<img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />

th:action

表單提交的地址

<form action="subscribe.html" th:action="@{/subscribe}">

????????標簽測試

????????模板:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><title>Title</title>
</head>
<body>
<div  th:text="${hello}" th:id="${hello.toUpperCase()}">xxxx</div>
<input th:value="${user.getUsername()}">
<hr>
<div th:object="${user}">
<span th:text="*{username}"></span></div><a th:href="" th:if="${user.getAge() == 2}" >年齡</a><a  th:class="${user.getAge() > 2}?'class1':'class2'" >年齡</a><p th:if="${user.score >= 60 and user.score < 85}">B</p>
<p th:if="${user.score < 60}">C</p>
<p th:if="${user.score > 85}">優秀</p><span th:switch="${user.gender}"><p th:case="1">男</p><p th:case="2">女</p>
</span><table><tr th:each="a,aState:${uList}"><td th:text="${a.username}"></td><td th:text="${a.password}"></td><td th:text="${aState.index}"></td></tr>
</table></body>
</html>

????????Controller中給數據

@RequestMapping("/success")
public String hello(HttpServletRequest req, HttpSession httpSession, Model model){model.addAttribute("hello","<h1>renliang</h1>");User user = new User();user.setPassword("111");user.setUsername("renliang");user.setAge(1);user.setScore(78);user.setGender(2);List<User> uList = new ArrayList<>();for (int i = 0; i < 10; i++){User u = new User();u.setUsername("renliang"+i);u.setPassword("111"+i);uList.add(u);}// httpSession.setAttribute("user", user);model.addAttribute("user", user);model.addAttribute("uList", uList);return "success";
}

1.4Springboot整合springmvc

? ??https://docs.spring.io/spring-boot/docs/2.0.2.RELEASE/reference/htmlsingle/#boot-features-spring-mvc

????????學習springmvc和springboot的自動配置我們必須對springmvc的組件足夠了解,起碼知道怎么用。Springmvc的組件基本都被springboot來做了自動的配置。

1.4.1Springmvc的自動解管理

  1. 中央轉發器(DispatcherServlet
  2. 控制器
  3. 視圖解析器
  4. 靜態資源訪問
  5. 消息轉換器
  6. 格式化
  7. 靜態資源管理
  8. 1.4.1.1中央轉發器
    1. ????????Xml無需配置

      1. <servlet><servlet-name>chapter2</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping><servlet-name>chapter2</servlet-name><url-pattern>/</url-pattern>
        </servlet-mapping>

        ????????中央轉發器被springboot自動接管,不再需要我們在web.xml中配置,我們現在的項目也不是web項目,也不存在web.xml,

        org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\

1.4.1.2控制器

????????控制器Controller在springboot的注解掃描范圍內自動管理。

1.4.1.3視圖解析器自動管理

Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

ContentNegotiatingViewResolver:組合所有的視圖解析器的;

曾經的配置文件無需再配

<bean id="de" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
????<property name="prefix" value="/WEB-INF/jsp/"></property>
????<property name="suffix" value="*.jsp"></property>
</bean>

????????源碼:

public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();resolver.setContentNegotiationManager((ContentNegotiationManager)beanFactory.getBean(ContentNegotiationManager.class));resolver.setOrder(-2147483648);return resolver;
}

????????當我們做文件上傳的時候我們也會發現multipartResolver自動被配置好的頁面

<form action="/upload" method="post" enctype="multipart/form-data"><input name="pic" type="file"><input type="submit">
</form>

????????Controller

@ResponseBody
@RequestMapping("/upload")
public String upload(@RequestParam("pic")MultipartFile file, HttpServletRequest request){String contentType = file.getContentType();String fileName = file.getOriginalFilename();/*System.out.println("fileName-->" + fileName);System.out.println("getContentType-->" + contentType);*///String filePath = request.getSession().getServletContext().getRealPath("imgupload/");String filePath = "D:/imgup/";try {this.uploadFile(file.getBytes(), filePath, fileName);} catch (Exception e) {// TODO: handle exception}return "success";
}public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {File targetFile = new File(filePath);if(!targetFile.exists()){targetFile.mkdirs();}FileOutputStream out = new FileOutputStream(filePath+fileName);out.write(file);out.flush();out.close();
}

文件上傳大小可以通過配置來修改

打開application.properties, 默認限制是10MB,我們可以任意修改

1.4.1.4靜態資源訪問

????????參見4.2

1.4.1.5消息轉換和格式化

????????Springboot自動配置了消息轉換器

????????格式化轉換器的自動注冊

????????時間類型我們可以在這里修改

????????在配置文件中指定好時間的模式我們就可以輸入了

1.4.1.6歡迎頁面的自動配置

????????Springboot自動指定resources下的index.html

1.4.2Springboot擴展springmvc?

????????在實際開發中springboot并非完全自動化,很多跟業務相關我們需要自己擴展,springboot給我提供了接口。

????????我們可以來通過實現WebMvcConfigurer接口來擴展

public interface WebMvcConfigurer {default void configurePathMatch(PathMatchConfigurer configurer) {}default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {}default void configureAsyncSupport(AsyncSupportConfigurer configurer) {}default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {}default void addFormatters(FormatterRegistry registry) {}default void addInterceptors(InterceptorRegistry registry) {}default void addResourceHandlers(ResourceHandlerRegistry registry) {}default void addCorsMappings(CorsRegistry registry) {}default void addViewControllers(ViewControllerRegistry registry) {}default void configureViewResolvers(ViewResolverRegistry registry) {}default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {}default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {}default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {}default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {}default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {}default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {}@Nullabledefault Validator getValidator() {return null;}@Nullabledefault MessageCodesResolver getMessageCodesResolver() {return null;}
}
1.4.2.1在容器中注冊視圖控制器(請求轉發)

????????創建一個MyMVCCofnig實現WebMvcConfigurer接口,實現一下addViewControllers方法我們完成通過/tx訪問,轉發到success.html工作

@Configuration
public class MyMVCCofnig implements WebMvcConfigurer{@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/tx").setViewName("success");}
}
1.4.2.2注冊格式化器

????????用來可以對請求過來的日期格式化的字符串來做定制化。當然通過application.properties配置也可以辦到。

@Override
public void addFormatters(FormatterRegistry registry) {registry.addFormatter(new Formatter<Date>() {@Overridepublic String print(Date date, Locale locale) {return null;}@Overridepublic Date parse(String s, Locale locale) throws ParseException {return new SimpleDateFormat("yyyy-MM-dd").parse(s);}});
}
1.4.2.3消息轉換器擴展fastjson

????????在pom.xml中引入fastjson

<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version>
</dependency>

????????配置消息轉換器,添加fastjson

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {FastJsonHttpMessageConverter fc = new FastJsonHttpMessageConverter();FastJsonConfig fastJsonConfig = new FastJsonConfig();fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);fc.setFastJsonConfig(fastJsonConfig);converters.add(fc);
}

????????在實體類上可以繼續控制

public class User
{private  String username;private  String password;private int age;private int score;private int gender;@JSONField(format = "yyyy-MM-dd")private Date date;}
1.4.2.4攔截器注冊

1.創建攔截器

public class MyInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("前置攔截");return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("后置攔截");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("最終攔截");}
}

攔截器注冊

@Override
public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/hello2");
}

1.5配置嵌入式服務器

1.5.1如何定制和修改Servlet容器的相關配置;

修改和server有關的配置(ServerProperties);

server.port=8081
server.context‐path=/tx
server.tomcat.uri‐encoding=UTF‐8

1.5.2注冊Servlet三大組件【Servlet、Filter、Listener】

????????由于SpringBoot默認是以jar包的方式啟動嵌入式的Servlet容器來啟動SpringBootweb應用,沒有web.xml文件。

????????1.servlet

//注冊三大組件
@Bean
public ServletRegistrationBean myServlet(){ServletRegistrationBean registrationBean = new ServletRegistrationBean(newMyServlet(),"/myServlet");return registrationBean;
}

????????2.?FilterRegistrationBean

@Bean
public FilterRegistrationBean myFilter(){FilterRegistrationBean registrationBean = new FilterRegistrationBean();registrationBean.setFilter(new MyFilter());registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));return registrationBean;
}

????????3.?ServletListenerRegistrationBean

@Bean
public ServletListenerRegistrationBean myListener(){ServletListenerRegistrationBean<MyListener> registrationBean = newServletListenerRegistrationBean<>(new MyListener());return registrationBean;
}

SpringBoot幫我們自動SpringMVC的時候,自動的注冊SpringMVC的前端控制器;DispatcherServlet
DispatcherServletAutoConfiguration中:

@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
@ConditionalOnBean(value = DispatcherServlet.class, name =
DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public ServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet) {ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet, this.serverProperties.getServletMapping());//默認攔截: / 所有請求;包靜態資源,但是不攔截jsp請求; /*會攔截jsp//可以通過server.servletPath來修改SpringMVC前端控制器默認攔截的請求路徑registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);registration.setLoadOnStartup(this.webMvcProperties.getServlet().getLoadOnStartup());if (this.multipartConfig != null) {registration.setMultipartConfig(this.multipartConfig);}return registration;
}

1.6使用外置的Servlet容器

嵌入式Servlet容器:應用打成可執行的jar

優點:簡單、便攜;

缺點:默認不支持JSP、優化定制比較復雜.;

????????外置的Servlet容器:外面安裝Tomcat---應用war包的方式打包;

步驟

1)、必須創建一個war項目;(利用idea創建好目錄結構)

2)、將嵌入式的Tomcat指定為provided?

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring‐boot‐starter‐tomcat</artifactId><scope>provided</scope>
</dependency>

3)配置項目的目錄結構

?

4)部署Tomcat

3)、必須編寫一個SpringBootServletInitializer的子類,并調用configure方法

public class ServletInitializer extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {//傳入SpringBoot應用的主程序return application.sources(SpringBoot04WebJspApplication.class);}
}

4)、啟動服務器就可以使用;

原理

jar包:執行SpringBoot主類的main方法,啟動ioc容器,創建嵌入式的Servlet容器;

war包:啟動服務器,服務器啟動SpringBoot應用【SpringBootServletInitializer】,啟動ioc容器;

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/73231.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/73231.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/73231.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Redis的緩存雪崩、緩存擊穿、緩存穿透與緩存預熱、緩存降級

一、緩存雪崩&#xff1a; 1、什么是緩存雪崩&#xff1a; 如果緩在某一個時刻出現大規模的key失效&#xff0c;那么就會導致大量的請求打在了數據庫上面&#xff0c;導致數據庫壓力巨大&#xff0c;如果在高并發的情況下&#xff0c;可能瞬間就會導致數據庫宕機。這時候如果…

Html5記憶翻牌游戲開發經驗分享

H5記憶翻牌游戲開發經驗分享 這里寫目錄標題 H5記憶翻牌游戲開發經驗分享前言項目概述技術要點解析1. 頁面布局&#xff08;HTML CSS&#xff09;響應式設計 2. 翻牌動畫效果3. 游戲邏輯實現狀態管理卡片配對檢測 開發技巧總結1. 模塊化設計2. 性能優化3. 用戶體驗 踩坑經驗擴…

【開源+代碼解讀】Search-R1:基于強化學習的檢索增強大語言模型框架3小時即可打造個人AI-search

大語言模型(LLMs)在處理復雜推理和實時信息檢索時面臨兩大挑戰:知識局限性(無法獲取最新外部知識)和檢索靈活性不足(傳統方法依賴固定檢索流程)。現有方法如檢索增強生成(RAG)和工具調用(Tool-Use)存在以下問題: RAG:單輪檢索導致上下文不足,無法適應多輪交互場景…

Linux網絡套接字編程——創建并綁定

目錄 網絡字節序 socket編程接口 socket bind 如果將進程比作一個房子&#xff0c;那套接字相當于是一扇門&#xff0c;通向與外界通信的通道。 在網絡中&#xff0c;如何理解套接字呢&#xff0c;時刻記住套接字是為了標識互聯網中的某一臺主機上的某一個進程&#xff0c…

1720. 解碼異或后的數組

解碼異或后的數組 題目描述嘗試做法 題目描述 未知整數數組 arr 由 n 個非負整數組成。 經編碼后變為長度為 n - 1 的另一個整數數組 encoded &#xff0c;其中 encoded[i] arr[i] XOR arr[i 1] 。例如&#xff0c;arr [1,0,2,1] 經編碼后得到 encoded [1,2,3] 。 給你編…

了解一下HTTP的短連接和長連接

在 HTTP 協議中&#xff0c;連接的方式主要分為長連接和短連接。這兩種連接方式的主要區別在于連接的生命周期和數據傳輸的效率。理解它們的差異對于優化 Web 應用的性能和資源利用至關重要。以下是 HTTP 長連接和短連接的詳細解釋。 1. 短連接&#xff08;HTTP/1.0&#xff0…

【WRF模擬】如何查看 WPS 的輸入靜態地理數據(二進制格式)?

查看 WPS 的輸入靜態地理數據方法總結 方法 1:使用 gdal_translate 將二進制數據轉換為 GeoTIFFgdal_translate 工具概述使用 gdal_translate 將二進制數據轉換為 GeoTIFF方法 2:使用 ncdump 查看 geo_em.dXX.nc方法 3:使用 Python xarray + matplotlib 可視化 geo_em.dXX.n…

Mybatis語法bug

select * from appointment where status ‘ACCEPTED’ and expire_time< now() idea顯示now&#xff08;&#xff09;這里一直報錯&#xff1a; 應為標記名稱 應為 Deepseek: 根據您的代碼和報錯信息分析&#xff0c;這是一個 MyBatis XML 文件中的 SQL 語法問題。具體原…

DeepSeek本機部署(基于Ollama和Docker管理)

目錄 一、ollama 與 docker 簡介 &#xff08;一&#xff09;ollama(Ollama) &#xff08;二&#xff09;docker 二、利用 ollama 和 docker 配置 deepseek-r1 的準備工作 &#xff08;一&#xff09;硬件需求 &#xff08;二&#xff09;軟件安裝 三、配置 deepseek-r1…

小程序 wxml 語法 —— 39 簡單雙向數據綁定

在 WXML 中&#xff0c;普通屬性的綁定是單向的&#xff0c;比如 <input value"{{ value }}" />&#xff0c;當數據發生改變時&#xff0c;頁面也會隨之發生變化&#xff0c;但是當用戶在輸入框中輸入最新內容&#xff0c;最新內容并不會同步給 value 數據&…

Linux第一次練習

1、找到你的Linux系統上的不同顏色的文件&#xff0c;每一種顏色的文件找到3個以上 藍色&#xff1a; 白色&#xff1a; 綠色&#xff1a; 紅色&#xff1a; 黃色&#xff1a; 2、設置一個ping的別名永久生效&#xff0c;設置一個ymd的別名date %F永久生效

《C#上位機開發從門外到門內》2-2:I2C總線協議及其應用詳解

文章目錄 一、引言二、I2C總線協議的基本概念三、I2C通信機制3.1 硬件結構與基本原理3.2 信號的起始與終止3.3 數據傳輸格式及時序3.4 時鐘同步與時鐘伸展 四、設備尋址與數據傳輸4.1 I2C設備尋址方式4.2 地址沖突及解決方法4.3 數據傳輸過程中的確認機制4.4 I2C數據幀結構與傳…

Trae IDE:解鎖 AI 驅動的高效編程體驗

Trae 介紹 Trae 是字節跳動推出的一款面向開發者的 AI 驅動的集成開發環境&#xff08;IDE&#xff09;&#xff0c;于 2024 年 1 月 19 日在新加坡正式發布海外版&#xff0c;2025 年 3 月 3 日發布國內版。海外版由字節跳動旗下的 SPRING&#xff08;SG&#xff09;PTE.LTD.…

玩轉python:通俗易懂掌握高級數據結構:collections模塊之namedtuple

引言 namedtuple是Python中collections模塊提供的一個強大工具&#xff0c;用于創建具有字段名的元組。它不僅具備元組的不可變性&#xff0c;還能通過字段名訪問元素&#xff0c;極大地提高了代碼的可讀性和可維護性。本文將詳細介紹namedtuple的關鍵用法和特性&#xff0c;并…

我的創作紀念日:730天的技術寫作之旅

我的創作紀念日&#xff1a;730天的技術寫作之旅 機緣 從一篇案例分析開始 2023年3月13日&#xff0c;我寫下了第一篇技術博客《軟考高級-系統分析師-案例分析-系統維護與設計模式》。那時的初心很簡單&#xff1a; 沉淀實戰經驗——在備考軟考系統分析師時&#xff0c;發現…

使用 Arduino 和 ESP8266 Wi-Fi 模塊發送電子郵件

使用 Arduino Uno 和 ESP8266 Wi-Fi 模塊發送電子郵件 我們正在邁向物聯網 (IoT) 世界。這項技術在電子和嵌入式系統中起著非常重要的作用。從任何微控制器或嵌入式系統發送電子郵件都是非常基本的事情,這在 IoT 中是必需的。因此,在本文中,我們將學習“如何使用 Wi-Fi 和…

golang算法二叉樹對稱平衡右視圖

100. 相同的樹 給你兩棵二叉樹的根節點 p 和 q &#xff0c;編寫一個函數來檢驗這兩棵樹是否相同。 如果兩個樹在結構上相同&#xff0c;并且節點具有相同的值&#xff0c;則認為它們是相同的。 示例 1&#xff1a; 輸入&#xff1a;p [1,2,3], q [1,2,3] 輸出&#xff1a…

c++介紹智能指針 十二(1)

普通指針&#xff1a;指向內存區域的地址變量。使用普通指針容易出現一些程序錯誤。 如果一個指針所指向的內存區域是動態分配的&#xff0c;那么這個指針變量離開了所在的作用域&#xff0c;這塊內存也不會自動銷毀。動態內存不進行釋放就會導致內存泄露。如果一個指針指向已…

亞馬遜COSMO算法解讀:新搜索時代的流量分配與DeepBI AI驅動的智能優化策略

亞馬遜COSMO算法的推出&#xff0c;標志著其搜索和推薦系統進入了智能化、個性化的新階段。該算法通過分析用戶購物習慣、搜索歷史、瀏覽行為等數據&#xff0c;為買家提供精準推薦&#xff0c;同時對賣家的運營策略提出了更高的要求。在這一背景下&#xff0c;AI驅動的DeepBI能…

C++編譯問題——1模板函數的實現必須在頭文件中

今天編譯數據結構時&#xff0c;遇見一個編譯錯誤 假設你有一個頭文件 SeqList.h 和一個源文件 SeqList.cpp。 SeqList.h #ifndef SEQLIST_H #define SEQLIST_H#include <stdexcept> #include <iostream>template<typename T> class SeqList { private:sta…