Elasticsearch Java客户端和Spring data elasticsearch-Elasticsearch文章三

news2024/10/5 19:09:46

文章目录

  • 官网
  • 版本
  • 组件版本说明
  • 实现代码地址
  • es Spring Data Repositories
    • 例子:
    • ElasticsearchRepository分析
  • es Spring Data Repositories 关键字
  • es Spring Data Repositories client 加载
    • rest风格客户端
    • 直接执行dsl例子
    • 响应式客户端-ReactiveElasticsearchClient
      • pom.xml
      • 例子
  • ES 原生方式加载客户端
    • pom.xml
    • 加载原生客户端
    • controller使用
    • 验证结果
  • 测试请求http文件-TestEs.http
  • 外传

官网

https://www.elastic.co/cn/

整合springboot看上一篇文章

版本

一定要对应好版本,Elasticsearch 的不同版本变化是真大,

https://docs.spring.io/spring-data/elasticsearch/docs/4.4.10/reference/html/

在这里插入图片描述

组件版本说明

Springboot: 2.7.10
spring-data-elasticsearch: 4.4.10
spring-boot-starter-data-elasticsearch: 2.7.10
elasticsearch-java: 7.17.9

实现代码地址

https://github.com/OrderDong/microservice-boot
分支:microservice-boot-1.0.6-es

microservice-boot-eleastic模块

在这里插入图片描述

所有pom.xml引用


<!--elastic search 7.17.9 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <!--高版本单独使用elasticsearch client -->
        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>7.17.9</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>jakarta.json</groupId>
            <artifactId>jakarta.json-api</artifactId>
            <version>2.0.1</version>
        </dependency>

        <!-- spring-data-elasticsearch 包含此包
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.17.9</version>
        </dependency>-->

        <!-- Reactive Infrastructure -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>io.projectreactor.netty</groupId>
            <artifactId>reactor-netty-http</artifactId>
        </dependency>

es Spring Data Repositories

类似于spring data封装的ORM框架,也可以理解为MVC的M层,当然,完全可以灵活应用,也支持rest层
https://docs.spring.io/spring-data/elasticsearch/docs/4.4.10/reference/html/#repositories

例子:

    //controller
    @PostMapping("/saveVisitLog")
    @ResponseBody
    public String saveVisitLog(@RequestBody VisitLog visitLog){
        VisitLog saveVisitLog = visitLogService.saveVisitLog(visitLog);
        log.info("----saveVisitLog----:{}", JSON.toJSONString(saveVisitLog));
        return JSON.toJSONString(saveVisitLog);
    }

    @GetMapping("/getVisitLogAll")
    @ResponseBody
    public String getVisitLogAll(){
        List<VisitLog> logList = visitLogService.findAll();
        log.info("----getVisitLogAll----:{}", JSON.toJSONString(logList));
        return JSON.toJSONString(logList);
    }


    //service
    @Override
    public VisitLog saveVisitLog(VisitLog visitLog) {
        return visitLogRepository.save(visitLog);
    }

    @Override
    public List<VisitLog> findAll() {
        Iterable<VisitLog> visitLogs = visitLogRepository.findAll();
        List<VisitLog> logs = new ArrayList<>();
        visitLogs.forEach(visitLog -> logs.add(visitLog));
        return logs;
    }

    //dao层
    @Repository
    public interface VisitLogRepository extends ElasticsearchRepository<VisitLog, String> {


    }

ElasticsearchRepository分析

CrudRepository最终继承了这个对象,这个对象被按照规则封装实现了具体的操作

我们可以看下ElasticsearchRepository实现了哪些方法:
在这里插入图片描述


@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {
    <S extends T> S save(S entity);

    <S extends T> Iterable<S> saveAll(Iterable<S> entities);

    Optional<T> findById(ID id);

    boolean existsById(ID id);

    Iterable<T> findAll();

    Iterable<T> findAllById(Iterable<ID> ids);

    long count();

    void deleteById(ID id);

    void delete(T entity);

    void deleteAllById(Iterable<? extends ID> ids);

    void deleteAll(Iterable<? extends T> entities);

    void deleteAll();
}


es Spring Data Repositories 关键字

spring data封装的ORM框架,很多接口继承的方法,也可以自定义方法,需要按照封装的规则自定义
https://docs.spring.io/spring-data/elasticsearch/docs/4.4.10/reference/html/#repositories.definition

例子:

    //controller
    //自定义查询
    @GetMapping("/getVisitLogByUserLoginId")
    @ResponseBody
    public String getVisitLogByUserLoginId(Integer userLoginId){
        List<VisitLog> logList = visitLogService.findByUserLoginId(userLoginId);
        log.info("----getVisitLogAll----:{}", JSON.toJSONString(logList));
        return JSON.toJSONString(logList);
    }



    //service impl
        @Override
    public List<VisitLog> findByUserLoginId(Integer userLoginId) {
        return visitLogRepository.findByUserLoginId(userLoginId);
    }


    //
    @Repository
    public interface VisitLogRepository extends ElasticsearchRepository<VisitLog, String> {

        //自定义规则,By--关键字,UserLoginId字段,翻译下,就是查询-find 通过--By  字段--UserLoginId
        //spring data repository会去解析,同样的方式自行查reference文档
        List<VisitLog> findByUserLoginId(Integer userLoginId);
    }


es Spring Data Repositories client 加载

当然,一般使用封装好的也有一定的麻烦事情,也可以自己加载客户端,使用spring data repository 加载,两种方式,但是7.17的版本把这种方式去掉了,
https://docs.spring.io/spring-data/elasticsearch/docs/4.4.10/reference/html/#elasticsearch.clients

rest风格客户端

The Java High Level REST Clientis the default client of Elasticsearch,it is configured likes hown:

package org.lwd.microservice.boot.es.config;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

/**
 * rest风格客户端
 * The Java High Level REST Client is the default client of Elasticsearch, it is configured like shown:
 *
 * @author weidong
 * @version V1.0.0
 * @since 2023/7/27
 */
@Configuration
public class EsRestHighLevelClientConfig extends AbstractElasticsearchConfiguration {

    @Value("${spring.elasticsearch.uris}")
    private String uris;

    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {

        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(uris)
                .build();

        return RestClients.create(clientConfiguration).rest();
    }

}

我们看下,那个bean可用(猜测一定被封装好了),AbstractElasticsearchConfiguration

public abstract class AbstractElasticsearchConfiguration extends ElasticsearchConfigurationSupport {

    /**
     * Return the {@link RestHighLevelClient} instance used to connect to the cluster. <br />
     *
     * @return never {@literal null}.
     */
    @Bean
    public abstract RestHighLevelClient elasticsearchClient();

    /**
     * Creates {@link ElasticsearchOperations}.
     *
     * @return never {@literal null}.
     */
    @Bean(name = { "elasticsearchOperations", "elasticsearchTemplate" })
    public ElasticsearchOperations elasticsearchOperations(ElasticsearchConverter elasticsearchConverter,
            RestHighLevelClient elasticsearchClient) {

        ElasticsearchRestTemplate template = new ElasticsearchRestTemplate(elasticsearchClient, elasticsearchConverter);
        template.setRefreshPolicy(refreshPolicy());

        return template;
    }
}

不知道各位发现没:@Bean(name = { “elasticsearchOperations”, “elasticsearchTemplate” })
用这个bean去操作

直接执行dsl例子

    //rest模版操作
    @Autowired
    ElasticsearchOperations elasticsearchOperations;


        //rest客户端模版
    @GetMapping("/getHighTempt")
    @ResponseBody
    public String getHighTempt(){
        Query query = new StringQuery("{ \"match\": { \"userLoginId\": 1 } } ");
        query.setPageable(PageRequest.of(0, 10));
        SearchHits<VisitLog>  searchHits = elasticsearchOperations.search(query,VisitLog.class);
        return JSON.toJSONString(searchHits);
    }


响应式客户端-ReactiveElasticsearchClient

  • The ReactiveElasticsearchClient is a non official driver based on WebClient.
  • It uses the request/response objects provided by the Elasticsearch core project.
  • Calls are directly operated on the reactive stack, not wrapping async (thread pool bound) responses into reactive types.
    如果不知道什么是响应式,自行百度

pom.xml


<!-- Reactive Infrastructure -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>io.projectreactor.netty</groupId>
            <artifactId>reactor-netty-http</artifactId>
        </dependency>

例子

package org.lwd.microservice.boot.es.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient;
import org.springframework.data.elasticsearch.client.reactive.ReactiveRestClients;
import org.springframework.data.elasticsearch.config.AbstractReactiveElasticsearchConfiguration;

/**
 * 响应式客户端
 * The ReactiveElasticsearchClient is a non official driver based on WebClient.
 * It uses the request/response objects provided by the Elasticsearch core project.
 * Calls are directly operated on the reactive stack, not wrapping async (thread pool bound) responses into reactive types.
 *
 * @author weidong
 * @version V1.0.0
 * @since 2023/7/28
 */
@Configuration
public class EsReactiveRestClientConfig extends AbstractReactiveElasticsearchConfiguration {

    @Value("${spring.elasticsearch.uris}")
    private String uris;

    @Bean
    @Override
    public ReactiveElasticsearchClient reactiveElasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(uris) //
                .build();
        return ReactiveRestClients.create(clientConfiguration);
    }
}



    //响应式模版操作
    @Autowired
    ReactiveElasticsearchOperations reactiveElasticsearchOperations;


    //响应式客户端
    @GetMapping("/getReactiveTemp")
    @ResponseBody
    public String getReactiveTemp(){
        Query query = new StringQuery("{ \"match\": { \"userLoginId\": 1 } } ");
        query.setPageable(PageRequest.of(0, 10));
        Flux<SearchHit<VisitLog>> result = reactiveElasticsearchOperations.search(query,VisitLog.class);
        return JSON.toJSONString(result);
    }

ES 原生方式加载客户端

从 ElasticSearch7.17 这个版本开始,原先的 Java 高级客户端
Java High Level REST Client 废弃了,不支持了。老实说,ElasticSearch 算是我用过的所有 Java 工具中,更新最为激进的一个了,在 Es7 中废弃了 TransportClient,7.17 又废弃了 TransportClient,那么现在用啥呢?现在的客户端叫做 Elasticsearch Java API Client。

Elasticsearch Java API Client 具有如下特性:

为所有 Elasticsearch APIs 提供强类型的请求和响应。
所有 API 都有阻塞和异步版本。
使用构建器模式,在创建复杂的嵌套结构时,可以编写简洁而可读的代码。
通过使用对象映射器(如 Jackson 或任何实现了 JSON-B 的解析器),实现应用程序类的无缝集成。
将协议处理委托给一个 http 客户端,如 Java Low Level REST Client,它负责所有传输级的问题。HTTP 连接池、重试、节点发现等等由它去完成。
关于第三点,松哥吐槽一句,确实简洁,但是可读性一般般吧。

另外还有两点需要注意:

Elasticsearch Java 客户端是向前兼容的,即该客户端支持与 Elasticsearch 的更大或相等的次要版本进行通信。
Elasticsearch Java 客户端只向后兼容默认的发行版本,并且没有做出保证。

pom.xml

<!--高版本单独使用elasticsearch client -->
        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>7.17.9</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>jakarta.json</groupId>
            <artifactId>jakarta.json-api</artifactId>
            <version>2.0.1</version>
        </dependency>

加载原生客户端

注意下,一定要用原生elasticsearch-java jar中的类

package org.lwd.microservice.boot.es.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 使用elasticsearch client 7.17.9
 *
 * @author weidong
 * @version V1.0.0
 * @since 2023/7/31
 */
@Configuration
public class EsRestClientConfig {
    @Value("${spring.elasticsearch.uris}")
    private String uris;

    @Bean
    public ElasticsearchClient initSyncRestClient() {
        RestClient restClient = RestClient.builder(HttpHost.create(uris)).build();
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        return client;
    }
}


controller使用


    @Autowired
    ElasticsearchClient elasticsearchClient;
    //elasticsearch client 7.17.9
    @GetMapping("/getRestTemp")
    @ResponseBody
    public String getRestTemp(){
        StringReader sr = new StringReader(
                "{\n" +
                        "  \"query\": { \"match\": {\n" +
                        "    \"userLoginId\": \"1\"\n" +
                        "  }}" +
                        "}"
        );
        //查询所有
       /* StringReader sr = new StringReader(
               "{\n" +
                       "  \"query\": {\n" +
                       "    \"match_all\" : {}\n" +
                       "  }\n" +
                       "}\n"
        );*/
        SearchRequest request = new SearchRequest.Builder().index(Arrays.asList(new String[]{"visit_log"}))
                .withJson(sr)
                .build();
        try {
            SearchResponse<VisitLog>  search = elasticsearchClient.search(request,VisitLog.class);
            System.out.println("search.toString() = " + search.toString());
            long took = search.took();
            System.out.println("took = " + took);
            boolean b = search.timedOut();
            System.out.println("b = " + b);
            ShardStatistics shards = search.shards();
            System.out.println("shards = " + shards);
            HitsMetadata<VisitLog> hits = search.hits();
            TotalHits total = hits.total();
            System.out.println("total = " + total);
            Double maxScore = hits.maxScore();
            System.out.println("maxScore = " + maxScore);
            List<Hit<VisitLog>> list = hits.hits();
            for (Hit<VisitLog> visitLogHit : list) {
                System.out.println("visitLogHit.source() = " + JSON.toJSONString(visitLogHit.source()));
                System.out.println("visitLogHit.score() = " + visitLogHit.score());
                System.out.println("visitLogHit.index() = " + visitLogHit.index());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


可以看到,直接把查询的 JSON 参数传进来也是可以的。这样我们就可以先在 Kibana 中写好脚本,然后直接将脚本拷贝到 Java 代码中来执行就行了。

验证结果

request [POST http://10.255.20.231:9200/visit_log/_search?typed_keys=true] returned 1 warnings: [299 Elasticsearch-7.17.9-ef48222227ee6b9e70e502f0f0daa52435ee634d "Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security."]
search.toString() = SearchResponse: {"took":0,"timed_out":false,"_shards":{"failed":0.0,"successful":1.0,"total":1.0,"skipped":0.0},"hits":{"total":{"relation":"eq","value":1},"hits":[{"_index":"visit_log","_id":"2","_score":0.9808291,"_type":"_doc","_source":"org.lwd.microservice.boot.es.entity.VisitLog@1bbbdce9"}],"max_score":0.9808291}}
took = 0
b = false
shards = ShardStatistics: {"failed":0.0,"successful":1.0,"total":1.0,"skipped":0.0}
total = TotalHits: {"relation":"eq","value":1}
maxScore = 0.9808291
visitLogHit.source() = {"_class":"org.lwd.microservice.boot.es.entity.VisitLog","createTime":"2023-07-27 16:34:36","id":2,"initialRequest":"http://localhost:8023","msgContent":"test es add2","serverHostName":"weidong","serverIpAddress":"127.0.0.1","tableName":"VisitLog","userLoginId":"1"}
visitLogHit.score() = 0.9808291
visitLogHit.index() = visit_log

测试请求http文件-TestEs.http


## 新增日志
POST http://localhost:8023/es/saveVisitLog
Content-Type: application/json

{
  "id": 3,
  "tableName": "VisitLog",
  "userLoginId": 3,
  "serverIpAddress": "127.0.0.1",
  "serverHostName": "weidong",
  "initialRequest": "http://localhost:8023",
  "msgContent": "test es add3",
  "createTime": "2023-07-27 16:34:36"
}


### 获取所有数据-不分页

GET http://localhost:8023/es/getVisitLogAll

### 获取所有数据-自定义查询规则

GET http://localhost:8023/es/getVisitLogByUserLoginId?userLoginId=1

### 获取所有数据-high rest

GET http://localhost:8023/es/getHighTempt

### 获取所有数据-reactive rest

GET http://localhost:8023/es/getReactiveTemp

### 获取所有数据-elasticsearch client 7.17.9

GET http://localhost:8023/es/getRestTemp


外传

😜 原创不易,如若本文能够帮助到您的同学
🎉 支持我:关注我+点赞👍+收藏⭐️
📝 留言:探讨问题,看到立马回复
💬 格言:己所不欲勿施于人 扬帆起航、游历人生、永不言弃!🔥

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

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

相关文章

【SLAM】LoFTR知多少

1. LoFTR: Detector-Free Local Feature Matching with Transformers PAPER 论文 | LoFTR: Detector-Free Local Feature Matching with Transformers 代码 | CODE: 关键词 | detector-free, local feature matching LoFTR知多少 1. LoFTR: Detector-Free Local Feature M…

DirectX SDK下载安装及开发环境设置

1 DirectX DirectX&#xff08;Direct eXtension&#xff0c;简称DX&#xff09;是由微软公司创建的多媒体编程接口&#xff0c;是一种应用程序接口&#xff08;API&#xff09;。DirectX可以让以windows为平台的游戏或多媒体程序获得更高的执行效率&#xff0c;加强3D图形和声…

15、两个Runner初始化器(ApplicationRunner接口和CommandLineRunner接口的实现类)

两个Runner初始化器 两个Runner初始化器——主要作用是对component组件来执行初始化 这里的Component组件我理解为是被Component注解修饰的类 Component //用这个注解修饰的类&#xff0c;意味着这个类是spring容器中的一个组件&#xff0c;springboot应用会自动加载该组件。 …

python-网络爬虫.regular

regular 正则表达式 (regular expression) 正则表达式(regular expression)描述了一种字符串匹配的模式 &#xff08;pattern&#xff09;&#xff0c; 可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串 中取出符合某个条件的子串等。 正则表达式是由普通…

gitlab配置webhook

一.前言 当需要做jenkins的自动化触发构建时&#xff0c;就需要配置gitlab的webhook功能&#xff0c;以下来展示以下如何配置gitlab的webhook&#xff0c;jenkins的配置就不在这里展示了&#xff0c;可以去看我devops文章的完整配置 二.配置 在新版本的gitlab中&#xff0c…

MySQL对表的操作以及数据类型

文章目录 创建删除表查看修改重命名表新增列修改列的属性删除列修改列名插入数据 数据类型enum和setenum和set的查找 创建 create table table_name ( field1 datatype, field2 datatype, field3 datatype ) charset 字符集 collate 校验规则 engine 存储引擎;其中field 表示列…

Linux - 环境变量

1.基本概念 环境变量(environment variables)一般是指在操作系统中用来指定操作系统运行环境的一些参数 如&#xff1a;我们在编写C/C代码的时候&#xff0c;在链接的时候&#xff0c;从来不知道我们的所链接的动态静态库在哪里&#xff0c;但 是照样可以链接成功&#xff0c;生…

超级个体新时代Web3space西南旗舰合伙人招募活动圆满落幕

7月30日&#xff0c;一场备受瞩目的超级个体新时代—Web3space西南旗舰合伙人招募活动在四川省成都市G1咖啡馆会议室成功举办。本次活动吸引了30余位Web3领域的从业者和爱好者参与&#xff0c;现场氛围十分热烈。 首先&#xff0c;CyberDAO执行合伙人JR老师主持了Web3space商业…

【AI实战】开源中文 llama2 来了,30 分钟搭建 130 亿参数大模型 Llama2-Chinese-13b-Chat

【AI实战】开源中文 llama2 来了&#xff0c;30 分钟搭建 130 亿参数大模型 Llama2-Chinese-13b-Chat 简介环境配置环境搭建依赖安装 代码及模型权重拉取拉取 Llama2-Chinese拉取 Llama2-Chinese-13b-Chat 模型权重及代码 终端测试页面测试安装 gradio加载模型并启动服务 国内 …

配置VS Code 使其支持vue项目断点调试

起因 每个应用&#xff0c;不论大小&#xff0c;都需要理解程序是如何运行失败的。当我们写的程序没有按照自己写的逻辑走的时候&#xff0c;我们就会逐步一一排查问题。在平常开发过程中我们可能会借助 console.log 来排查,但是现在我们可以借助 VS Code 断点来调试项目。 前…

Linux下查阅帮助文档必学命令 man

Linux操作系统的使用中,我们经常会遇到很多问题,这个时候查询文档的能力至关重要,黄老师来推荐大家使用man,这时我们必须掌握的查阅能力: 最常用的命令: man 名称 man 数字(1~9) 名称 这里的数字分别代表:

JavaWeb 项目实现(四) 验证旧密码

1.验证旧密码 步骤很简单&#xff0c;从Session中取到当前密码&#xff0c;和修改密码界面得到的旧密码对比&#xff0c;判断是否相等。 特别之处在于实现用到了Ajax&#xff0c;可以不刷新整个页面的情况下与Web服务器进行通信。 2.Ajax Ajax&#xff08;Asynchronous Java…

使用Gunicorn+Nginx部署Flask项目

部署-开发机上的准备工作 确认项目没有bug。用pip freeze > requirements.txt将当前环境的包导出到requirements.txt文件中&#xff0c;方便部署的时候安装。将项目上传到服务器上的/srv目录下。这里以git为例。使用git比其他上传方式&#xff08;比如使用pycharm&#xff…

深度学习之用PyTorch实现线性回归

代码 # 调用库 import torch# 数据准备 x_data torch.Tensor([[1.0], [2.0], [3.0]]) # 训练集输入值 y_data torch.Tensor([[2.0], [4.0], [6.0]]) # 训练集输出值# 定义线性回归模型 class LinearModel(torch.nn.Module):def __init__(self):super(LinearModel, self)._…

nodejs安装及多版本安装与TS环境搭建

nodejs安装及多版本安装与TS环境搭建 方法一&#xff1a; 普通安装nodejs,确定只能安装一个。网址&#xff1a;链接: 官网 不同系统下安装&#xff1a;不同系统下的nodejs 方法二&#xff1a; 借助工具nvm&#xff0c;安装多个nodejs&#xff0c;随时切换nodejs版本 什么是…

禁止别人调试自己的前端页面代码

✨ 目录 &#x1f388; 为啥要禁止&#xff1f;&#x1f388; 无限 debugger&#x1f388; 无限 debugger 的对策&#x1f388; 禁止断点的对策&#x1f388; 忽略执行的代码&#x1f388; 忽略执行代码的对策&#x1f388; 终极增强防调试代码 &#x1f388; 为啥要禁止&#…

简约好看的帮助中心创建案例,赶紧点赞收藏!

在线帮助中心创建案例是提供用户支持和解决问题的有效方式之一。一个简约好看的帮助中心案例能够帮助用户快速找到需要的信息并解决问题&#xff0c;同时也能提升用户体验&#xff0c;增加点赞和收藏的可能性。 帮助中心创建案例分享&#xff1a; 酷学院&#xff1a; 酷渲&a…

item_get-KS-获取商品详情

一、接口参数说明&#xff1a; item_get-根据ID取商品详情 &#xff0c;点击更多API调试&#xff0c;请移步注册API账号点击获取测试key和secret 公共参数 请求地址: https://api-gw.onebound.cn/ks/item_get 名称类型必须描述keyString是调用key&#xff08;http://o0b.cn/…

‘vite‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件。

1.切换到工程目录下 2.执行npm install(最关键的一步了&#xff01;&#xff01;) 3. 最后直接运行&#xff1a;npm run dev 4.浏览器直接打开就行了&#xff01;

断网监测网关可以自动重启路由器

网络设备监测系统是一种用于监测远程网络设备状态的设备&#xff0c;它可以通过断网、断电和网线监测等多种方式进行监测。该系统支持同时监测7台网络设备&#xff0c;并且具有1路继电器输出&#xff0c;可以用于自动重启或者远程重启网络设备。 网络设备监测系统内置微型处理器…