SpringBoot는 SFTP 클라이언트를 어떻게 통합하여 파일을 업로드하고 다운로드합니까?
Background
프로젝트 개발에서 SFTP 서비스는 일반적인 파일 저장에 거의 사용되지 않지만 파트너가 SFTP를 사용하여 프로젝트에 파일을 저장하거나 SFTP를 통해 파일 데이터 상호 작용을 구현하는 경우도 배제되지 않습니다.
내가 접한 프로젝트에서 은행, 보험사 등의 파트너는 SFTP 서비스를 사용하여 프로젝트의 파일 데이터와 상호 작용합니다.
친구의 SFTP 서비스에 성공적으로 연결하려면 자체 프로젝트에 SFTP 클라이언트 도구 세트를 구현해야 합니다. 일반적으로 Jsch를 사용하여 SFTP 클라이언트를 구현합니다.
Dependency
<!--执行远程操作--> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> <!--链接池--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.11.1</version> </dependency>
먼저 SFTP 클라이언트 구현의 초석인 jsch
종속성을 도입해야 합니다. 두 번째로 다시 작업을 방지하기 위해 링크 풀 도구를 도입합니다. SFTP 명령을 실행할 때마다 링크를 생성하고 풀링을 사용하여 리소스를 소비하는 생성 작업을 최적화합니다. jsch
依赖,这个是我们实现SFTP客户端的基石;其次我们引入了链接池工具,为了避免每次执行SFTP命令都要重新创建链接,我们使用池化的方式优化了比较消耗资源的创建操作。
创建工具类
为了更好的使用SFTP工具,我们把jsch
中关于SFTP的相关功能提炼出来,做了一次简单的封装,做成了我们可以直接使用的工具类。
里面只有两类方法:
1.创建Session与开启Session;
session创建好后,还不能创建channel,需要开启session后才能创建channel;
2.创建channel与开启channel;
channel也是一样,创建好的channel需要开启后才能真正地执行命令;
public class JschUtil { /** * 创建session * * @param userName 用户名 * @param password 密码 * @param host 域名 * @param port 端口 * @param privateKeyFile 密钥文件 * @param passphrase 口令 * @return * @throws AwesomeException */ public static Session createSession(String userName, String password, String host, int port, String privateKeyFile, String passphrase) throws AwesomeException { return createSession(new JSch(), userName, password, host, port, privateKeyFile, passphrase); } /** * 创建session * * @param jSch * @param userName 用户名 * @param password 密码 * @param host 域名 * @param port 端口 * @param privateKeyFile 密钥 * @param passphrase 口令 * @return * @throws AwesomeException */ public static Session createSession(JSch jSch, String userName, String password, String host, int port, String privateKeyFile, String passphrase) throws AwesomeException { try { if (!StringUtils.isEmpty(privateKeyFile)) { // 使用密钥验证方式,密钥可以是有口令的密钥,也可以是没有口令的密钥 if (!StringUtils.isEmpty(passphrase)) { jSch.addIdentity(privateKeyFile, passphrase); } else { jSch.addIdentity(privateKeyFile); } } // 获取session Session session = jSch.getSession(userName, host, port); if (!StringUtils.isEmpty(password)) { session.setPassword(password); } // 不校验域名 session.setConfig("StrictHostKeyChecking", "no"); return session; } catch (Exception e) { throw new AwesomeException(500, "create session fail"); } } /** * 创建session * * @param jSch * @param userName 用户名 * @param password 密码 * @param host 域名 * @param port 端口 * @return * @throws AwesomeException */ public static Session createSession(JSch jSch, String userName, String password, String host, int port) throws AwesomeException { return createSession(jSch, userName, password, host, port, StringUtils.EMPTY, StringUtils.EMPTY); } /** * 创建session * * @param jSch * @param userName 用户名 * @param host 域名 * @param port 端口 * @return * @throws AwesomeException */ private Session createSession(JSch jSch, String userName, String host, int port) throws AwesomeException { return createSession(jSch, userName, StringUtils.EMPTY, host, port, StringUtils.EMPTY, StringUtils.EMPTY); } /** * 开启session链接 * * @param jSch * @param userName 用户名 * @param password 密码 * @param host 域名 * @param port 端口 * @param privateKeyFile 密钥 * @param passphrase 口令 * @param timeout 链接超时时间 * @return * @throws AwesomeException */ public static Session openSession(JSch jSch, String userName, String password, String host, int port, String privateKeyFile, String passphrase, int timeout) throws AwesomeException { Session session = createSession(jSch, userName, password, host, port, privateKeyFile, passphrase); try { if (timeout >= 0) { session.connect(timeout); } else { session.connect(); } return session; } catch (Exception e) { throw new AwesomeException(500, "session connect fail"); } } /** * 开启session链接 * * @param userName 用户名 * @param password 密码 * @param host 域名 * @param port 端口 * @param privateKeyFile 密钥 * @param passphrase 口令 * @param timeout 链接超时时间 * @return * @throws AwesomeException */ public static Session openSession(String userName, String password, String host, int port, String privateKeyFile, String passphrase, int timeout) throws AwesomeException { Session session = createSession(userName, password, host, port, privateKeyFile, passphrase); try { if (timeout >= 0) { session.connect(timeout); } else { session.connect(); } return session; } catch (Exception e) { throw new AwesomeException(500, "session connect fail"); } } /** * 开启session链接 * * @param jSch * @param userName 用户名 * @param password 密码 * @param host 域名 * @param port 端口 * @param timeout 链接超时时间 * @return * @throws AwesomeException */ public static Session openSession(JSch jSch, String userName, String password, String host, int port, int timeout) throws AwesomeException { return openSession(jSch, userName, password, host, port, StringUtils.EMPTY, StringUtils.EMPTY, timeout); } /** * 开启session链接 * * @param userName 用户名 * @param password 密码 * @param host 域名 * @param port 端口 * @param timeout 链接超时时间 * @return * @throws AwesomeException */ public static Session openSession(String userName, String password, String host, int port, int timeout) throws AwesomeException { return openSession(userName, password, host, port, StringUtils.EMPTY, StringUtils.EMPTY, timeout); } /** * 开启session链接 * * @param jSch * @param userName 用户名 * @param host 域名 * @param port 端口 * @param timeout 链接超时时间 * @return * @throws AwesomeException */ public static Session openSession(JSch jSch, String userName, String host, int port, int timeout) throws AwesomeException { return openSession(jSch, userName, StringUtils.EMPTY, host, port, StringUtils.EMPTY, StringUtils.EMPTY, timeout); } /** * 开启session链接 * * @param userName 用户名 * @param host 域名 * @param port 端口 * @param timeout 链接超时时间 * @return * @throws AwesomeException */ public static Session openSession(String userName, String host, int port, int timeout) throws AwesomeException { return openSession(userName, StringUtils.EMPTY, host, port, StringUtils.EMPTY, StringUtils.EMPTY, timeout); } /** * 创建指定通道 * * @param session * @param channelType * @return * @throws AwesomeException */ public static Channel createChannel(Session session, ChannelType channelType) throws AwesomeException { try { if (!session.isConnected()) { session.connect(); } return session.openChannel(channelType.getValue()); } catch (Exception e) { throw new AwesomeException(500, "open channel fail"); } } /** * 创建sftp通道 * * @param session * @return * @throws AwesomeException */ public static ChannelSftp createSftp(Session session) throws AwesomeException { return (ChannelSftp) createChannel(session, ChannelType.SFTP); } /** * 创建shell通道 * * @param session * @return * @throws AwesomeException */ public static ChannelShell createShell(Session session) throws AwesomeException { return (ChannelShell) createChannel(session, ChannelType.SHELL); } /** * 开启通道 * * @param session * @param channelType * @param timeout * @return * @throws AwesomeException */ public static Channel openChannel(Session session, ChannelType channelType, int timeout) throws AwesomeException { Channel channel = createChannel(session, channelType); try { if (timeout >= 0) { channel.connect(timeout); } else { channel.connect(); } return channel; } catch (Exception e) { throw new AwesomeException(500, "connect channel fail"); } } /** * 开启sftp通道 * * @param session * @param timeout * @return * @throws AwesomeException */ public static ChannelSftp openSftpChannel(Session session, int timeout) throws AwesomeException { return (ChannelSftp) openChannel(session, ChannelType.SFTP, timeout); } /** * 开启shell通道 * * @param session * @param timeout * @return * @throws AwesomeException */ public static ChannelShell openShellChannel(Session session, int timeout) throws AwesomeException { return (ChannelShell) openChannel(session, ChannelType.SHELL, timeout); } enum ChannelType { SESSION("session"), SHELL("shell"), EXEC("exec"), X11("x11"), AGENT_FORWARDING("auth-agent@openssh.com"), DIRECT_TCPIP("direct-tcpip"), FORWARDED_TCPIP("forwarded-tcpip"), SFTP("sftp"), SUBSYSTEM("subsystem"); private final String value; ChannelType(String value) { this.value = value; } public String getValue() { return this.value; } } }
SFTP链接池化
我们通过实现BasePooledObjectFactory
类来池化通道ChannelSftp
。这并不是真正池化的代码,下面的代码只是告知池化管理器如何创建对象和销毁对象。
static class SftpFactory extends BasePooledObjectFactory<ChannelSftp> implements AutoCloseable { private Session session; private SftpProperties properties; // 初始化SftpFactory // 里面主要是创建目标session,后续可用通过这个session不断地创建ChannelSftp。 SftpFactory(SftpProperties properties) throws AwesomeException { this.properties = properties; String username = properties.getUsername(); String password = properties.getPassword(); String host = properties.getHost(); int port = properties.getPort(); String privateKeyFile = properties.getPrivateKeyFile(); String passphrase = properties.getPassphrase(); session = JschUtil.createSession(username, password, host, port, privateKeyFile, passphrase); } // 销毁对象,主要是销毁ChannelSftp @Override public void destroyObject(PooledObject<ChannelSftp> p) throws Exception { p.getObject().disconnect(); } // 创建对象ChannelSftp @Override public ChannelSftp create() throws Exception { int timeout = properties.getTimeout(); return JschUtil.openSftpChannel(this.session, timeout); } // 包装创建出来的对象 @Override public PooledObject<ChannelSftp> wrap(ChannelSftp channelSftp) { return new DefaultPooledObject<>(channelSftp); } // 验证对象是否可用 @Override public boolean validateObject(PooledObject<ChannelSftp> p) { return p.getObject().isConnected(); } // 销毁资源,关闭session @Override public void close() throws Exception { if (Objects.nonNull(session)) { if (session.isConnected()) { session.disconnect(); } session = null; } } }
为了实现真正的池化操作,我们还需要以下代码:
1.我们需要在SftpClient对象中创建一个GenericObjectPool
对象池,这个才是真正的池子,它负责创建和存储所有的对象。
2.我们还需要提供资源销毁的功能,也就是实现AutoCloseable
,在服务停止时,需要把相关的资源销毁。
public class SftpClient implements AutoCloseable { private SftpFactory sftpFactory; GenericObjectPool<ChannelSftp> objectPool; // 构造方法1 public SftpClient(SftpProperties properties, GenericObjectPoolConfig<ChannelSftp> poolConfig) throws AwesomeException { this.sftpFactory = new SftpFactory(properties); objectPool = new GenericObjectPool<>(this.sftpFactory, poolConfig); } // 构造方法2 public SftpClient(SftpProperties properties) throws AwesomeException { this.sftpFactory = new SftpFactory(properties); SftpProperties.PoolConfig config = properties.getPool(); // 默认池化配置 if (Objects.isNull(config)) { objectPool = new GenericObjectPool<>(this.sftpFactory); } else { // 自定义池化配置 GenericObjectPoolConfig<ChannelSftp> poolConfig = new GenericObjectPoolConfig<>(); poolConfig.setMaxIdle(config.getMaxIdle()); poolConfig.setMaxTotal(config.getMaxTotal()); poolConfig.setMinIdle(config.getMinIdle()); poolConfig.setTestOnBorrow(config.isTestOnBorrow()); poolConfig.setTestOnCreate(config.isTestOnCreate()); poolConfig.setTestOnReturn(config.isTestOnReturn()); poolConfig.setTestWhileIdle(config.isTestWhileIdle()); poolConfig.setBlockWhenExhausted(config.isBlockWhenExhausted()); poolConfig.setMaxWait(Duration.ofMillis(config.getMaxWaitMillis())); poolConfig.setTimeBetweenEvictionRuns(Duration.ofMillis(config.getTimeBetweenEvictionRunsMillis())); objectPool = new GenericObjectPool<>(this.sftpFactory, poolConfig); } } // 销毁资源 @Override public void close() throws Exception { // 销毁链接池 if (Objects.nonNull(this.objectPool)) { if (!this.objectPool.isClosed()) { this.objectPool.close(); } } this.objectPool = null; // 销毁sftpFactory if (Objects.nonNull(this.sftpFactory)) { this.sftpFactory.close(); } } }
SFTP链接池的使用
我们已经对链接池进行了初始化,下面我们就可以从链接池中获取我们需要的ChannelSftp
来实现文件的上传下载了。
下面实现了多种文件上传和下载的方式:
1.直接把本地文件上传到SFTP服务器的指定路径;
2.把InputStream输入流提交到SFTP服务器指定路径中;
3.可以针对以上两种上传方式进行进度的监测;
4.把SFTP服务器中的指定文件下载到本地机器上;
5.把SFTP服务器˙中的文件写入指定的输出流;
6.针对以上两种下载方式,监测下载进度;
/** * 上传文件 * * @param srcFilePath * @param targetDir * @param targetFileName * @return * @throws AwesomeException */ public boolean uploadFile(String srcFilePath, String targetDir, String targetFileName) throws AwesomeException { return uploadFile(srcFilePath, targetDir, targetFileName, null); } /** * 上传文件 * * @param srcFilePath * @param targetDir * @param targetFileName * @param monitor * @return * @throws AwesomeException */ public boolean uploadFile(String srcFilePath, String targetDir, String targetFileName, SftpProgressMonitor monitor) throws AwesomeException { ChannelSftp channelSftp = null; try { // 从链接池获取对象 channelSftp = this.objectPool.borrowObject(); // 如果不存在目标文件夹 if (!exist(channelSftp, targetDir)) { mkdirs(channelSftp, targetDir); } channelSftp.cd(targetDir); // 上传文件 if (Objects.nonNull(monitor)) { channelSftp.put(srcFilePath, targetFileName, monitor); } else { channelSftp.put(srcFilePath, targetFileName); } return true; } catch (Exception e) { throw new AwesomeException(500, "upload file fail"); } finally { if (Objects.nonNull(channelSftp)) { // 返还对象给链接池 this.objectPool.returnObject(channelSftp); } } } /** * 上传文件到目标文件夹 * * @param in * @param targetDir * @param targetFileName * @return * @throws AwesomeException */ public boolean uploadFile(InputStream in, String targetDir, String targetFileName) throws AwesomeException { return uploadFile(in, targetDir, targetFileName, null); } /** * 上传文件,添加进度监视器 * * @param in * @param targetDir * @param targetFileName * @param monitor * @return * @throws AwesomeException */ public boolean uploadFile(InputStream in, String targetDir, String targetFileName, SftpProgressMonitor monitor) throws AwesomeException { ChannelSftp channelSftp = null; try { channelSftp = this.objectPool.borrowObject(); // 如果不存在目标文件夹 if (!exist(channelSftp, targetDir)) { mkdirs(channelSftp, targetDir); } channelSftp.cd(targetDir); if (Objects.nonNull(monitor)) { channelSftp.put(in, targetFileName, monitor); } else { channelSftp.put(in, targetFileName); } return true; } catch (Exception e) { throw new AwesomeException(500, "upload file fail"); } finally { if (Objects.nonNull(channelSftp)) { this.objectPool.returnObject(channelSftp); } } } /** * 下载文件 * * @param remoteFile * @param targetFilePath * @return * @throws AwesomeException */ public boolean downloadFile(String remoteFile, String targetFilePath) throws AwesomeException { return downloadFile(remoteFile, targetFilePath, null); } /** * 下载目标文件到本地 * * @param remoteFile * @param targetFilePath * @return * @throws AwesomeException */ public boolean downloadFile(String remoteFile, String targetFilePath, SftpProgressMonitor monitor) throws AwesomeException { ChannelSftp channelSftp = null; try { channelSftp = this.objectPool.borrowObject(); // 如果不存在目标文件夹 if (!exist(channelSftp, remoteFile)) { // 不用下载了 return false; } File targetFile = new File(targetFilePath); try (FileOutputStream outputStream = new FileOutputStream(targetFile)) { if (Objects.nonNull(monitor)) { channelSftp.get(remoteFile, outputStream, monitor); } else { channelSftp.get(remoteFile, outputStream); } } return true; } catch (Exception e) { throw new AwesomeException(500, "upload file fail"); } finally { if (Objects.nonNull(channelSftp)) { this.objectPool.returnObject(channelSftp); } } } /** * 下载文件 * * @param remoteFile * @param outputStream * @return * @throws AwesomeException */ public boolean downloadFile(String remoteFile, OutputStream outputStream) throws AwesomeException { return downloadFile(remoteFile, outputStream, null); } /** * 下载文件 * * @param remoteFile * @param outputStream * @param monitor * @return * @throws AwesomeException */ public boolean downloadFile(String remoteFile, OutputStream outputStream, SftpProgressMonitor monitor) throws AwesomeException { ChannelSftp channelSftp = null; try { channelSftp = this.objectPool.borrowObject(); // 如果不存在目标文件夹 if (!exist(channelSftp, remoteFile)) { // 不用下载了 return false; } if (Objects.nonNull(monitor)) { channelSftp.get(remoteFile, outputStream, monitor); } else { channelSftp.get(remoteFile, outputStream); } return true; } catch (Exception e) { throw new AwesomeException(500, "upload file fail"); } finally { if (Objects.nonNull(channelSftp)) { this.objectPool.returnObject(channelSftp); } } } /** * 创建文件夹 * * @param channelSftp * @param dir * @return */ protected boolean mkdirs(ChannelSftp channelSftp, String dir) { try { String pwd = channelSftp.pwd(); if (StringUtils.contains(pwd, dir)) { return true; } String relativePath = StringUtils.substringAfter(dir, pwd); String[] dirs = StringUtils.splitByWholeSeparatorPreserveAllTokens(relativePath, "/"); for (String path : dirs) { if (StringUtils.isBlank(path)) { continue; } try { channelSftp.cd(path); } catch (SftpException e) { channelSftp.mkdir(path); channelSftp.cd(path); } } return true; } catch (Exception e) { return false; } } /** * 判断文件夹是否存在 * * @param channelSftp * @param dir * @return */ protected boolean exist(ChannelSftp channelSftp, String dir) { try { channelSftp.lstat(dir); return true; } catch (Exception e) { return false; } }
集成到SpringBoot中
我们可以通过java config
的方式,把我们已经实现好的SftpClient
类实例化到Spring IOC
容器中来管理,以便让开发人员在整个项目中通过@Autowired
jsch
에서 SFTP 관련 기능을 추출하고, 간단한 캡슐화를 거쳐, 직접 사용할 수 있는 종류의 도구를 만들었습니다. 방법에는 두 가지만 있습니다. 1. 세션 생성 및 세션 열기 🎜🎜세션이 생성된 후에는 채널을 생성할 수 없으며, 채널을 생성하기 전에 세션을 열어야 합니다. 2. 채널 생성 및 열기 🎜🎜 명령이 실제로 실행되기 전에 생성된 채널을 열어야 합니다. 🎜import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * @author zouwei * @className SftpProperties * @date: 2022/8/19 下午12:12 * @description: */ @Data @Configuration @ConfigurationProperties(prefix = "sftp.config") public class SftpProperties { // 用户名 private String username; // 密码 private String password; // 主机名 private String host; // 端口 private int port; // 密钥 private String privateKeyFile; // 口令 private String passphrase; // 通道链接超时时间 private int timeout; // 链接池配置 private PoolConfig pool; @Data public static class PoolConfig { //最大空闲实例数,空闲超过此值将会被销毁淘汰 private int maxIdle; // 最小空闲实例数,对象池将至少保留2个空闲对象 private int minIdle; //最大对象数量,包含借出去的和空闲的 private int maxTotal; //对象池满了,是否阻塞获取(false则借不到直接抛异常) private boolean blockWhenExhausted; // BlockWhenExhausted为true时生效,对象池满了阻塞获取超时,不设置则阻塞获取不超时,也可在borrowObject方法传递第二个参数指定本次的超时时间 private long maxWaitMillis; // 创建对象后是否验证对象,调用objectFactory#validateObject private boolean testOnCreate; // 借用对象后是否验证对象 validateObject private boolean testOnBorrow; // 归还对象后是否验证对象 validateObject private boolean testOnReturn; // 定时检查期间是否验证对象 validateObject private boolean testWhileIdle; //定时检查淘汰多余的对象, 启用单独的线程处理 private long timeBetweenEvictionRunsMillis; //jmx监控,和springboot自带的jmx冲突,可以选择关闭此配置或关闭springboot的jmx配置 private boolean jmxEnabled; } }
ChannelSftp</ code> <code>BasePooledObjectFactory
클래스를 구현하여 구현합니다. 이것은 실제 풀링 코드가 아닙니다. 다음 코드는 풀 관리자에게 개체를 생성하고 삭제하는 방법을 알려줍니다. 🎜import com.example.awesomespring.exception.AwesomeException; import com.example.awesomespring.sftp.SftpClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author zouwei * @className SftpConfig * @date: 2022/8/19 下午12:12 * @description: */ @Configuration public class SftpConfig { @Autowired private SftpProperties properties; // 创建SftpClient对象 @Bean(destroyMethod = "close") @ConditionalOnProperty(prefix = "sftp.config") public SftpClient sftpClient() throws AwesomeException { return new SftpClient(properties); } }
GenericObjectPool
개체 풀을 만들어야 합니다. 모든 객체를 생성하고 저장하는 일을 담당합니다. 🎜🎜2. 리소스 파기 기능, 즉 AutoCloseable
을 구현해야 합니다. 서비스가 중지되면 해당 리소스도 파기해야 합니다. 🎜rrreee🎜SFTP 링크 풀 사용🎜🎜링크 풀을 초기화했습니다. 이제 파일 업로드 및 다운로드에 필요한 ChannelSftp
를 링크 풀에서 가져올 수 있습니다. 🎜🎜다양한 파일 업로드 및 다운로드 방법은 다음과 같습니다. 🎜🎜1. SFTP 서버의 지정된 경로에 로컬 파일을 직접 업로드합니다. 🎜🎜2. SFTP 서버의 지정된 경로에 입력 스트림을 제출합니다. 🎜3. 위의 두 가지 업로드 방법의 진행 상황을 모니터링할 수 있습니다. 🎜🎜4. SFTP 서버의 지정된 파일을 로컬 시스템에 다운로드합니다. 🎜 🎜6 .위의 두 가지 다운로드 방법에 대한 다운로드 진행 상황을 모니터링합니다. 🎜rrreee🎜SpringBoot에 통합🎜🎜 java config
방법을 사용하여 우리가 구현한 SftpClient
를 구현할 수 있습니다. 클래스는 Spring IOC
컨테이너에서 인스턴스화되고 관리되므로 개발자는 @Autowired
를 통해 전체 프로젝트에서 직접 사용할 수 있습니다. 🎜🎜Configuration🎜rrreee🎜java Bean 주입🎜rrreee🎜위 코드를 사용하면 SFTP 클라이언트를 직접 사용하여 프로젝트 내 어디에서나 파일을 업로드하고 다운로드할 수 있습니다. 🎜위 내용은 SpringBoot는 SFTP 클라이언트를 어떻게 통합하여 파일을 업로드하고 다운로드합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Jasypt 소개 Jasypt는 개발자가 최소한의 노력으로 프로젝트에 기본 암호화 기능을 추가할 수 있게 해주며 암호화 작동 방식에 대한 깊은 이해가 필요하지 않은 단방향 및 양방향 암호화에 대한 높은 보안을 제공합니다. 표준 기반 암호화 기술. 비밀번호, 텍스트, 숫자, 바이너리 암호화... Spring 기반 애플리케이션, 개방형 API와의 통합에 적합하며 모든 JCE 공급자와 함께 사용할 수 있습니다... 다음 종속성을 추가합니다: com.github.ulisesbocchiojasypt-spring-boot-starter2. Jasypt의 이점은 코드가 유출되더라도 데이터 소스를 보장할 수 있어 시스템 보안을 보호합니다.

사용 시나리오 1. 주문이 성공적으로 이루어졌으나 30분 이내에 결제가 이루어지지 않았습니다. 결제 시간이 초과되어 주문이 자동으로 취소되었습니다. 2. 주문이 서명되었으며 서명 후 7일 동안 평가가 수행되지 않았습니다. 주문 시간이 초과되어 평가되지 않으면 시스템은 기본적으로 긍정적 평가로 설정됩니다. 3. 판매자가 5분 동안 주문을 받지 않으면 주문이 취소됩니다. 문자 메시지 알림이 전송됩니다... 지연이 길고 실시간 성능이 낮은 시나리오의 경우 작업 예약을 사용하여 정기적인 폴링 처리를 수행할 수 있습니다. 예: xxl-job 오늘은 다음을 선택하겠습니다.

1. Redis는 분산 잠금 원칙과 분산 잠금이 필요한 이유를 구현합니다. 분산 잠금에 대해 이야기하기 전에 분산 잠금이 필요한 이유를 설명해야 합니다. 분산 잠금의 반대는 독립형 잠금입니다. 다중 스레드 프로그램을 작성할 때 공유 변수를 동시에 작동하여 발생하는 데이터 문제를 방지하기 위해 일반적으로 잠금을 사용하여 공유 변수를 상호 제외합니다. 공유 변수의 사용 범위는 동일한 프로세스에 있습니다. 동시에 공유 리소스를 운영해야 하는 여러 프로세스가 있는 경우 어떻게 상호 배타적일 수 있습니까? 오늘날의 비즈니스 애플리케이션은 일반적으로 마이크로서비스 아키텍처입니다. 이는 하나의 애플리케이션이 여러 프로세스를 배포한다는 의미이기도 합니다. 여러 프로세스가 MySQL에서 동일한 레코드 행을 수정해야 하는 경우 잘못된 작업으로 인해 발생하는 더티 데이터를 방지하려면 배포가 필요합니다. 현재 소개할 스타일은 잠겨 있습니다. 포인트를 얻고 싶다

Springboot가 파일을 읽지만 jar 패키지로 패키징한 후 최신 개발에 액세스할 수 없습니다. springboot가 파일을 jar 패키지로 패키징한 후 파일을 읽을 수 없는 상황이 발생합니다. 그 이유는 패키징 후 파일의 가상 경로 때문입니다. 유효하지 않으며 읽기를 통해서만 액세스할 수 있습니다. 파일은 리소스 publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input 아래에 있습니다.

SpringBoot와 SpringMVC는 모두 Java 개발에서 일반적으로 사용되는 프레임워크이지만 둘 사이에는 몇 가지 분명한 차이점이 있습니다. 이 기사에서는 이 두 프레임워크의 기능과 용도를 살펴보고 차이점을 비교할 것입니다. 먼저 SpringBoot에 대해 알아봅시다. SpringBoot는 Spring 프레임워크를 기반으로 하는 애플리케이션의 생성 및 배포를 단순화하기 위해 Pivotal 팀에서 개발되었습니다. 독립 실행형 실행 파일을 구축하는 빠르고 가벼운 방법을 제공합니다.

Springboot+Mybatis-plus가 다중 테이블 추가 작업을 수행하기 위해 SQL 문을 사용하지 않을 때 내가 직면한 문제는 테스트 환경에서 생각을 시뮬레이션하여 분해됩니다. 매개 변수가 있는 BrandDTO 개체를 생성하여 배경으로 매개 변수 전달을 시뮬레이션합니다. Mybatis-plus에서 다중 테이블 작업을 수행하는 것은 매우 어렵다는 것을 Mybatis-plus-join과 같은 도구를 사용하지 않으면 해당 Mapper.xml 파일을 구성하고 냄새나고 긴 ResultMap만 구성하면 됩니다. 해당 SQL 문을 작성합니다. 이 방법은 번거로워 보이지만 매우 유연하며 다음을 수행할 수 있습니다.

1. RedisAPI 기본 직렬화 메커니즘인 RedisTemplate1.1을 사용자 정의합니다. API 기반 Redis 캐시 구현은 데이터 캐싱 작업에 RedisTemplate 템플릿을 사용합니다. 여기서 RedisTemplate 클래스를 열고 클래스의 소스 코드 정보를 봅니다. 키 선언, 값의 다양한 직렬화 방법, 초기 값은 비어 있음 @NullableprivateRedisSe

프로젝트에서는 일부 구성 정보가 필요한 경우가 많습니다. 이 정보는 테스트 환경과 프로덕션 환경에서 구성이 다를 수 있으며 실제 비즈니스 상황에 따라 나중에 수정해야 할 수도 있습니다. 이러한 구성은 코드에 하드 코딩할 수 없습니다. 예를 들어 이 정보를 application.yml 파일에 작성할 수 있습니다. 그렇다면 코드에서 이 주소를 어떻게 얻거나 사용합니까? 2가지 방법이 있습니다. 방법 1: @Value 주석이 달린 ${key}를 통해 구성 파일(application.yml)의 키에 해당하는 값을 가져올 수 있습니다. 이 방법은 마이크로서비스가 상대적으로 적은 상황에 적합합니다. 프로젝트, 업무가 복잡할 때는 논리
