springboot项目搭建集成 redis/跨域/远程请求

news2024/9/22 15:35:43

目录

一,创建maven项目

1,左上角file > new > maven project 

2,next 到 创建 Group id 和  Artifact id​编辑​编辑

二,配置springboot

1,配置pom文件,

2,创建启动类

3,配置 yml 文件

三,集成 Redis

1,yml追加配置

2,对 Redis 做些代码配置

3,spring 注解@Configuration类中编写代码访问

4,过滤器 ,获取Redis的代码 注:过滤路径在yml配置文件中配置

5,配置 Redis 数据

6,页面访问controller

四,集成 跨域

1,yml文件配置需要跨域的路径端口

2,过滤器,获取跨域代码

3,spring 注解@Configuration类中编写代码访问

五,集成 远程请求

1,封装工具类

2,通用工具类方法sendRequest


一,创建maven项目

1,左上角file > new > maven project 
2,next 到 创建 Group id 和  Artifact id

        

二,配置springboot

1,配置pom文件,
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.3</version>
	</parent>
	<groupId>cn.yilixun.jt.econtract</groupId>
	<artifactId>jt-econtract</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba.fastjson2</groupId>
			<artifactId>fastjson2</artifactId>
			<version>2.0.12</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>5.8.12</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
		</dependency>

		<dependency>
			<groupId>com.squareup.okhttp3</groupId>
			<artifactId>okhttp-sse</artifactId>
		</dependency>
		<dependency>
			<groupId>com.squareup.okhttp3</groupId>
			<artifactId>okhttp</artifactId>
		</dependency>

		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.5.4.1</version>
		</dependency>

		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
			<version>3.5.4.1</version>
		</dependency>

		<dependency>
			<groupId>org.mybatis.scripting</groupId>
			<artifactId>mybatis-velocity</artifactId>
			<version>2.1.2</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-validation</artifactId>
		</dependency>
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>3.3.0</version>
		</dependency>

		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.2.1</version>
		</dependency>

		<!-- 分页插件 -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
			<version>1.4.2</version>
		</dependency>

		<!-- easypoi的支持 -->
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-base</artifactId>
			<version>3.2.0</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<mainClass>cn.yilixun.jt.econtract.portal.EcontractPortalStartup</mainClass>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>repackage</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
2,创建启动类
package cn.yilixun.jt.econtract.portal;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;

/**
 * Hello world!
 *
 */
@SpringBootApplication
@ComponentScan(basePackages = { "cn.yilixun.*" })
@MapperScan("cn.yilixun.jt.econtract.portal.mapper")
@EnableConfigurationProperties
public class EcontractPortalStartup {
	
	public static void main(String[] args) {
		SpringApplication.run(EcontractPortalStartup.class, args);
	}
}
3,配置 yml 文件

application.yml

spring:
  application:
    name: portal
  profiles:
    active: dev
  jackson:
    default-property-inclusion: non_null
    time-zone: GMT+8
  main:
    allow-bean-definition-overriding: true 
mybatis-plus:
  mapper-locations: classpath:/mybatis/*.xml
  type-aliases-package: cn.yilixun.jt.econtract.portal.info
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#日志配置
logging:
  config: classpath:logback-spring.xml
  level:
    org.springframework: warn
access:
  ignore-pattern: /*|
  control:
    allow:
      origin: http://localhost:8080

application-dev.yml

server:
  port: 10000
  servlet:
    context-path: /econtract
logging:
  file:
    path: D:\logs
spring:
  redis:
    host: 172.16.1.205
    port: 6379
    database: 8
    password: "Redis12#$56"
    timeout: 10s
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://172.16.1.205:3306/jt_econtract?serverTimezone=GMT%2B8&remarks=true&useInformationSchema=true&tinyInt1isBit=true&allowMultiQueries=true
    username: jt_econtract
    password: JTecontract@2024.

至此,springboot项目生成完毕

三,集成 Redis

1,yml追加配置

2,对 Redis 做些代码配置
package cn.yilixun.jt.econtract.portal.cache;

import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

public class RedisCache {
	
	public final static long REDIS_EXPIRE_TIME = 7200L;
	
	public final static String REDIS_KEY_USER_TOKEN = "user-token:";
	
	public final static String REDIS_KEY_BASE_DATA = "base-data:";

	private RedisTemplate<String, String> redisTemplate;
	
	public RedisCache(RedisTemplate<String, String> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	public void hset(final String key, final String hashKey, final Object value) {
		this.redisTemplate.opsForHash().put(key, hashKey, JSON.toJSONString(value));
	}
	
	public String hget(final String key, final String hashKey) {
		HashOperations<String,Object,Object> operation = this.redisTemplate.opsForHash();
		if (operation != null && operation.get(key, hashKey) != null) {
			return (String)operation.get(key, hashKey);
		}
		return null;
	}

	public void set(final String key, final Object value) {
		this.redisTemplate.opsForValue().set(key, JSON.toJSONString(value));
	}

	public void set(final String key, final Object value, final long timeout, final TimeUnit timeUnit) {
		this.redisTemplate.opsForValue().set(key, JSON.toJSONString(value), timeout, timeUnit);
	}

	public String get(final String key) {
		ValueOperations<String, String> operation = this.redisTemplate.opsForValue();
		return operation.get(key);
	}

	public boolean expire(final String key, final long timeout) {
		return this.expire(key, timeout, TimeUnit.SECONDS);
	}

	public boolean expire(final String key, final long timeout, final TimeUnit unit) {
		return this.redisTemplate.expire(key, timeout, unit);
	}

	public boolean delete(final String key) {
		return this.redisTemplate.delete(key);
	}
	
	public void createUserToken(String token, Object user) {
		if (user != null) {
			this.set(RedisCache.REDIS_KEY_USER_TOKEN + token, user, RedisCache.REDIS_EXPIRE_TIME, TimeUnit.SECONDS);
		}
	}
	public JSONObject getLoginUserInfo(String token) {
		Object obj = this.get(RedisCache.REDIS_KEY_USER_TOKEN + token);
		if (obj != null) {
			this.expire(RedisCache.REDIS_KEY_USER_TOKEN + token, RedisCache.REDIS_EXPIRE_TIME, TimeUnit.SECONDS);
			return JSONObject.parseObject(obj.toString());
		}
		return null;
	}

}
3,spring 注解@Configuration类中编写代码访问
package cn.yilixun.jt.econtract.portal.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import cn.yilixun.jt.econtract.portal.cache.RedisCache;
import cn.yilixun.jt.econtract.portal.filter.SimpleCorsFilter;

@Configuration
public class PropertiesConfig {
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Bean
	public RedisCache redisCache() {
		return new RedisCache(this.redisTemplate);
	}

	
}
4,过滤器 ,获取Redis的代码 注:过滤路径在yml配置文件中配置
package cn.yilixun.jt.econtract.portal.filter;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson2.JSONObject;

import cn.yilixun.jt.econtract.portal.cache.RedisCache;



@Component
@WebFilter(urlPatterns = {"/*"})
@Order(1)
public class AccessVerifyFilter implements Filter {
    @Value("${access.ignore-pattern:}")
    private String ignoreLoginUri;
    @Autowired
    private RedisCache redisCache;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("User-Token");
        if (!StringUtils.hasLength(token)) {
            token = req.getParameter("userToken");
        }
        JSONObject user = redisCache.getLoginUserInfo(token);
        String path = req.getServletPath();
        if (!this.isIgnoreUri(this.ignoreLoginUri, path) && (user == null || user.isEmpty())) {
            JSONObject erInfo = new JSONObject();
            erInfo.put("state", 900);
            erInfo.put("code", "302");
            this.writeResponse(response, erInfo);
            return;
        }

        chain.doFilter(request, response);
    }

    private void writeResponse(ServletResponse response, JSONObject msg) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(msg.toJSONString());
        response.getWriter().flush();
    }

    private boolean isIgnoreUri(String patternsStr, String path) {
        if (StringUtils.hasLength(patternsStr)) {
            String[] patterns = patternsStr.split("\\|");
            if (patterns.length > 0) {
                for (String p : patterns) {
                    if (StringUtils.hasLength(p) && Pattern.matches(p.replace("*", ".*"), path)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}
5,配置 Redis 数据

6,页面访问controller
package cn.yilixun.jt.econtract.portal.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSONObject;

import cn.yilixun.jt.econtract.portal.cache.RedisCache;
import cn.yilixun.jt.econtract.portal.response.ResponseResult;


@RestController
@RequestMapping("/")
public class PortalController {

    @Autowired
    protected RedisCache redisCache;
    
    @GetMapping("/getBaseInfo")
    public JSONObject dictList(HttpServletRequest req) {
    	String token = req.getHeader("User-Token");
        if (!StringUtils.hasLength(token)) {
            token = req.getParameter("userToken");
        }
        JSONObject user = redisCache.getLoginUserInfo(token);
        return ResponseResult.success(user);
    }

}

        

至此,Redis 集成结束

四,集成 跨域

1,yml文件配置需要跨域的路径端口

2,过滤器,获取跨域代码

package cn.yilixun.jt.econtract.portal.filter;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * SimpleCORSFilter.
 * @Title:SimpleCORSFilter.java
 * @Description SimpleCORSFilter.java
 */
public class SimpleCorsFilter implements Filter {
    
    private String originUrl;
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        originUrl = filterConfig.getInitParameter("originUrl");
    }
    
    /**
     * 请求过滤器.
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest re = (HttpServletRequest) req;
        String url = re.getHeader("Origin");
        String[] urlArray = originUrl.split(",");
        if (Arrays.asList(urlArray).contains(url)) {
            response.setHeader("Access-Control-Allow-Origin", url);
        }
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,token,Access-Token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, res);
    } 
}
3,spring 注解@Configuration类中编写代码访问
package cn.yilixun.jt.econtract.portal.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import cn.yilixun.jt.econtract.portal.cache.RedisCache;
import cn.yilixun.jt.econtract.portal.filter.SimpleCorsFilter;

@Configuration
public class PropertiesConfig {

	@Value("${access.control.allow.origin}")
	private String originUrl;


	/**
	 * 跨域过滤器.
	 * 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Bean
	public FilterRegistrationBean filterRegist() {
		FilterRegistrationBean frBean = new FilterRegistrationBean();
		frBean.setFilter(new SimpleCorsFilter());
		frBean.addUrlPatterns("/*");
		frBean.addInitParameter("originUrl", originUrl);
		return frBean;
	}
}

至此,跨域集成结束

五,集成 远程请求

1,封装工具类
package cn.yilixun.jt.econtract.portal.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSONObject;

import lombok.extern.log4j.Log4j2;

@Log4j2
public class RestTemplateUtil {
	
    /**
     * 发送请求.
     *
     * @param method not null
     * @return
     */
    public static JSONObject sendRequest(String url, HttpMethod method, Object bodyParams, JSONObject headerParams) throws Exception {
        log.info("RestTemplateUtil.sendRequest start :: [url] = " + url + ", [method] = " + method);
        RestTemplate rest = new RestTemplate();
        rest.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
        HttpEntity<Object> request = RestTemplateUtil.getRequestEntity(bodyParams, headerParams);
        ResponseEntity<JSONObject> res = rest.exchange(url, method, request, JSONObject.class);
        if (res == null || res.getBody() == null) {
            throw new Exception("获取api数据异常");
        }
        log.info("RestTemplateUtil.sendRequest end :: " + res.getBody().toString());
        return res.getBody();
    }

    private static HttpEntity<Object> getRequestEntity(Object rbp, JSONObject rhp) {
        MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        if (rhp != null && !rhp.isEmpty()) {
            for (String key : rhp.keySet()) {
                header.add(key, rhp.getString(key));
            }
        }
        return new HttpEntity<>(rbp, header);
    }
    
    /**
     * 发送请求.
     *
     * @param method not null
     * @return
     */
    public static JSONObject sendRequestMap(String url, HttpMethod method, Map<String, Object> requestBodyParams, Map<String, String> requestHeaderParams) throws Exception {
        log.info("RestTemplateUtil.sendRequest start :: [url] = " + url + ", [method] = " + method);
        RestTemplate rest = new RestTemplate();
        rest.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
        HttpEntity<Map<String, Object>> request = getRequest(requestBodyParams, requestHeaderParams);
        if (method == HttpMethod.GET) {
            url = convetUrl(url, requestBodyParams);
        }
        ResponseEntity<JSONObject> res = rest.exchange(url, method, request, JSONObject.class);
        if (res == null || res.getBody() == null) {
            throw new Exception("获取api数据异常");
        }
        log.info("RestTemplateUtil.sendRequest end :: " + res.getBody().toString());
        return res.getBody();
    }

    /**
     * 请求配置.
     *
     * @Param :authorization
     * @Return :HttpEntity
     */
    private static HttpEntity<Map<String, Object>> getRequest(Map<String, Object> rbp, Map<String, String> rhp) {
        Map<String, Object> body = new HashMap<>();
        HttpHeaders header = new HttpHeaders();
        if (rbp != null && !rbp.isEmpty()) {
            for (String key : rbp.keySet()) {
                body.put(key, rbp.get(key));
            }
        }
        if (rhp != null && !rhp.isEmpty()) {
            for (String key : rhp.keySet()) {
                header.add(key, rhp.get(key));
            }
        }
        return new HttpEntity<>(body, header);
    }

    public static class WxMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
        /**
         * RestTemplate 把数据从 HttpResponse 转换成 Object 的时候,找不到合适的 HttpMessageConverter 来转换
         * 需要继承 MappingJackson2HttpMessageConverter 并在构造过程中设置其支持的 MediaType 类型.
         */
        public  WxMappingJackson2HttpMessageConverter() {
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
            setSupportedMediaTypes(mediaTypes);
        }
    }

    /**
     * get请求url拼接参数.
     * @Param :authorization
     * @Return :HttpEntity
     */
    public static String convetUrl(String url, Map<String, Object> param) {
        String paramUrl = "";
        if (param != null) {
            for (Map.Entry<String, Object> e : param.entrySet()) {
                paramUrl+=(e.getKey() + "=" + e.getValue() + "&");
            }
        }
        if (StringUtils.hasLength(paramUrl)) {
            return url + "?" + paramUrl.substring(0, paramUrl.length() - 1);
        }
        return url;
    }
}
2,通用工具类方法sendRequest
private void executeAfterStartup() {
        JSONObject jsonObject = null;
        try {
            jsonObject = RestTemplateUtil.sendRequest("http://localhost:8080/aaaaa", HttpMethod.POST,new JSONObject(), null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("10".equals(jsonObject.get("code").toString())) {
          JSONObject jsonObject  = jsonObject.get("data");
        }
    }

至此,远程请求集成结束

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1994090.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

五段式S型算法笔记

设定已知&#xff1a;v0 vmax j&#xff1b; 减加速段&#xff1a;tm到tmax 加加速段&#xff1a;0到tm tm&#xff1a;中点时间 vm&#xff1a;中点速度 vmax&#xff1a;最大速度&#xff1b; j加速度的斜率 -j相反加速度的斜率 这个图首先说明&#xff…

大数据面试SQL(六):共同使用ip用户检测问题

文章目录 共同使用ip用户检测问题 一、题目 二、分析 三、SQL实战 四、样例数据参考 共同使用ip用户检测问题 一、题目 现有用户登录日志表&#xff0c;记录了每个用户登录的IP地址&#xff0c;请查询共同使用过3个及以上IP的用户对。 样例数据&#xff1a; 结果数据&…

NSSCTF练习记录:[SWPUCTF 2021 新生赛]jicao

题目&#xff1a; 这段PHP代码的意思是&#xff1a; 对index.php文件进行语法高亮显示&#xff0c;插入flag.php文件&#xff0c;变量id的值为POST传递的值&#xff0c;变量json的值为GET传递的json类型的值。当id值为wllmNB且json中含有键为“x”&#xff0c;值为“wllm”的时…

【Android】安卓四大组件之Service用法

文章目录 使用Handler更新UIService基本特点启动方式非绑定式服务使用步骤 绑定式服务步骤 生命周期非绑定式启动阶段结束阶段 绑定式启动阶段结束阶段 前台Service使用步骤结束结束Service本身降级为普通Service降级为普通Service 使用Handler更新UI 主线程创建Handler对象&a…

文件描述符中设置FD_CLOEXEC的用处

linux中&#xff0c;父进程fork出子进程&#xff0c;子进程本身会继承父进程的所有文件描述符。若子进程再调用exec系列函数转化为新的进程实体&#xff0c;其实父进程的描述符对其没有意义。此时文件上只需要设置FD_CLOEXEC即可。 下面是例子说明&#xff1a; #include <…

vue3、uniapp-vue3模块自动导入

没有使用插件 使用插件,模块自动导入 安装: npm i -D unplugin-auto-importvite.config.js (uniapp没有此文件,在项目根目录下创建) import { defineConfig } from "vite"; import uni from "dcloudio/vite-plugin-uni"; import AutoImport from &qu…

SpringBoot 自定义 Starter 实现

一、定义&#xff0c;什么是Starter SpringBoot Starter 是”一站式服务&#xff08;one-stop service&#xff09;“的依赖 Jar 包&#xff1a; 包含 Spring 以及相关技术&#xff08;比如Redis&#xff09;的所有依赖提供了自动配置的功能&#xff0c;开箱即用提供了良好的…

7. Kubernetes核心资源之Service服务实战

**service分类 : ** **ClusterIP : ** 默认类型&#xff0c;自动分配一个【仅集群内部】可以访问的虚拟IP **NodePort : ** 对外访问应用使用&#xff0c;在ClusterIP基础上为Service在每台机器上绑定一个端口&#xff0c;就可以通过: ipNodePort来访问该服务 **LoadBalanc…

[24年新算法]NRBO-XGBoost回归+交叉验证基于牛顿拉夫逊优化算法-XGBoost多变量回归预测

[24年新算法]NRBO-XGBoost回归交叉验证基于牛顿拉夫逊优化算法-XGBoost多变量回归预测 多输入单输出 程序已调试好&#xff0c;无需更改代码替换数据直接使用&#xff01;&#xff01;&#xff01;数据格式为excel格式&#xff01;如下。 中文注释清晰&#xff0c;图很丰富 …

2. C++的指针作用

目录 1.问题描述及分析 2.结论 不同类型所产生的指针在C语言中有什么作用&#xff1f;带着这个疑问&#xff0c;对C的指针进行简介。 1.问题描述及分析 在如下的一段代码中&#xff0c;分别有4个指针&#xff0c;这四个指针有什么不一样的地方么&#xff1f; class ZooAni…

Unity物理模块 之 ​2D刚体

本文仅作笔记学习和分享&#xff0c;不用做任何商业用途本文包括但不限于unity官方手册&#xff0c;unity唐老狮等教程知识&#xff0c;如有不足还请斧正​ 1.刚体是什么 在 Unity 中&#xff0c;刚体&#xff08;Rigidbody&#xff09; 是物理引擎中最基本的组件之一&#x…

Python 函数(2)

2、函数 2.1、函数传递列表 将列表传递给函数后&#xff0c;函数就能直接访问其内容。 下列为一个实例&#xff1a;将一个名字列表传递给一个名为greet_users()的函数&#xff0c;这个函数将会向列表中的每一个元素执行相应的信息。 def greet_users(name):for name in name…

1.2 C 语言开发环境 CLion 的安装(含 Windows 和 Mac )

目录 1 C 语言的由来 2 安装 MinGW 编译器 3 Windows 中安装 CLion 开发环境 3.1 安装 CLion 开发环境 3.2 运行试用 30 天 3.3 新建项目​ 3.​4 激活 3.5 汉化 4 Mac 中安装 Clion 开发环境 4.1 安装 CLion 开发环境 4.2 运行试用 30 天 4.3 新建项目 ​4.4 激活…

RuoYi-Vue源码阅读(三):用户相关模块

文章目录 1 用户角色权限信息 getInfo1.1 后端代码实现步骤1.1.1 获取用户角色权限信息1.1.2 获取用户的角色集合 1.2 前端代码实现步骤 2 获取用户路由信息 getRouters2.1 后端代码实现步骤2.1.1 获取菜单目录2.1.2 构建前端路由所需要的菜单 2.2 前端代码实现步骤 3 参考链接…

设计模式20-备忘录模式

设计模式20-备忘录 动机定义与结构定义结构 C代码推导优缺点应用场景总结备忘录模式和序列化备忘录模式1. **动机**2. **实现方式**3. **应用场景**4. **优点**5. **缺点** 序列化1. **动机**2. **实现方式**3. **应用场景**4. **优点**5. **缺点** 对比总结 动机 在软件构建过…

Redis相关面试题(二)

一、BIT中不同命令使用的场景 Sring Seesion会话业务缓存分布式锁&#xff1a;为了防止用户同时登录多个设备进行操作 Int 计数器限流全局唯一ID Hash 电商购物车 BitMap 用户签到 List 消息队列 ZSet 排行榜 二、什么是缓存击穿&#xff0c;缓存穿透&#xff0c;…

C++--类和对象(一)

C是一个面向对象的编程语言&#xff0c;而面向对象编程有四大特性&#xff1a;封装&#xff0c;抽象&#xff0c;继承&#xff0c;多态。类和对象就是对应其中的封装&#xff0c;在C中将数据和对数据的操作都封装在一个class&#xff08;类&#xff09;的结构体中。 目录 类的…

【C++二分查找】2187. 完成旅途的最少时间

本文涉及的基础知识点 C二分查找 LeetCode2187. 完成旅途的最少时间 给你一个数组 time &#xff0c;其中 time[i] 表示第 i 辆公交车完成 一趟旅途 所需要花费的时间。 每辆公交车可以 连续 完成多趟旅途&#xff0c;也就是说&#xff0c;一辆公交车当前旅途完成后&#xf…

TCP如何建立长连接

文章目录 TCP建立长连接长连接和短连接长连接的优势TCP KEEPALIVE 心跳包心跳检测步骤 断线重连断线重连函数实现 实例服务端客户端程序功能演示效果 TCP建立长连接 长连接和短连接 长连接是指不论TCP的客户端和服务器之间是否有数据传输&#xff0c;都保持建立的TCP连接&…

Docker最佳实践(三):安装mysql

大家好&#xff0c;欢迎各位工友。 本篇呢我们就来演示一下如何在Docker中部署MySQL容器&#xff0c;可以按照以下步骤进行&#xff1a; 1. 搜索镜像 首先搜索MySQL镜像&#xff0c;可以使用以下命令&#xff1a; docker search mysql2. 拉取镜像 根据需求选择MySQL或Maria…