Sider de complemento basado en navegador, que utiliza el código generado por chatgpt3.5 para conectarse a Redis

 1. Instalación

Primero instale el complemento Sider en el navegador, los pasos de instalación específicos https://www.423xz.com/gaoxiao/3949.html

Cargos: Hay varias veces al día en las que se usa chatgpt3.5 de forma gratuita, pero se debe pagar chatgpt4.

2. Utilice los pasos:

Uso después de la instalación, pasos específicos:

1. Encuentra la extensión

 2. Encuentra el lado correspondiente.

 3. Seleccione la versión 3.5 e ingrese las palabras clave en el cuadro de entrada.

 3. Genere contenido específico a través de palabras clave.

Aquí quiero generar el código para que springboot se conecte a redis, usando el método de plantilla. Para ser más preciso, especifiqué directamente el número de versión específico para evitar ambigüedades.

Palabras rápidas:

用spring boot2.5编写连接redis4.0的demo,使用模板方法。

Obtenga el resultado de la respuesta:

下面是一个使用Spring Boot 2.5连接Redis 4.0的示例代码,使用RedisTemplate作为模板方法:

首先,确保在pom.xml文件中添加以下依赖:

<dependencies>
    <!-- Spring Boot -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>
接下来,在application.properties文件中配置Redis连接信息:

# Redis
spring.redis.host=localhost
spring.redis.port=6379
然后,创建一个Redis配置类,用于配置Redis连接:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;

@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private int redisPort;

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(redisHost, redisPort);
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Object.class));
        return redisTemplate;
    }
}
最后,创建一个使用RedisTemplate的示例类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisDemo {

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public RedisDemo(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void setValue(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}
现在,你可以在其他类中使用RedisDemo类来操作Redis了:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    private final RedisDemo redisDemo;

    @Autowired
    public DemoApplication(RedisDemo redisDemo) {
        this.redisDemo = redisDemo;
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    public void run(String... args) {
        String key = "myKey";
        String value = "myValue";

        redisDemo.setValue(key, value);

        Object retrievedValue = redisDemo.getValue(key);
        System.out.println(retrievedValue);
    }
}
这是一个简单的使用Spring Boot 2.5连接Redis 4.0的示例,使用了模板方法RedisTemplate来操作Redis。你可以根据自己的需求进行修改和扩展。

 Análisis de los resultados de la respuesta:

La respuesta escribe el contenido principal clave, pero si desea usarlo directamente, debe colocarlo usted mismo en el proyecto, que puede usarse como programación auxiliar.

Pero también debe tenerse en cuenta que el método de conexión aquí es muy simple, solo hay un valor para establecer y obtener, y no existe un método de operación específico para tipos de datos detallados.

4. Optimización y mejora de resultados

Debido a que los resultados anteriores son algo generales, continuaré y solicitaré operaciones en tipos de datos específicos. Para probar si tiene la capacidad de comprender el contexto, hablaré directamente sobre el funcionamiento del tipo de datos detallado sin ninguna otra indicación, el efecto es que tiene la capacidad de comprender el contexto y proporciona resultados más detallados.

Palabra rápida 2:

方法再详细一些,增加针对具体数据类型的操作方法

 Resultado de la respuesta:

好的,下面是一个更详细的示例,包括了针对具体数据类型的操作方法:

首先,确保在pom.xml文件中添加以下依赖:

<dependencies>
    <!-- Spring Boot -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>
接下来,在application.properties文件中配置Redis连接信息:

# Redis
spring.redis.host=localhost
spring.redis.port=6379
然后,创建一个Redis配置类,用于配置Redis连接:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private int redisPort;

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(redisHost, redisPort);
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Object.class));
        return redisTemplate;
    }
}
然后,创建一个使用RedisTemplate的示例类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class RedisDemo {

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public RedisDemo(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void setValue(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void setList(String key, List<Object> values) {
        redisTemplate.opsForList().leftPushAll(key, values);
    }

    public List<Object> getList(String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    public void setHash(String key, Map<String, Object> values) {
        redisTemplate.opsForHash().putAll(key, values);
    }

    public Map<Object, Object> getHash(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    public void setSet(String key, Set<Object> values) {
        redisTemplate.opsForSet().add(key, values.toArray());
    }

    public Set<Object> getSet(String key) {
        return redisTemplate.opsForSet().members(key);
    }
}
现在,你可以在其他类中使用RedisDemo类来操作Redis了:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@SpringBootApplication
public class DemoApplication {

    private final RedisDemo redisDemo;

    @Autowired
    public DemoApplication(RedisDemo redisDemo) {
        this.redisDemo = redisDemo;
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    public void run(String... args) {
        String key = "myKey";
        String value = "myValue";

        redisDemo.setValue(key, value);

        Object retrievedValue = redisDemo.getValue(key);
        System.out.println(retrievedValue);

        String listKey = "myList";
        redisDemo.setList(listKey, Arrays.asList("value1", "value2", "value3"));

        List<Object> retrievedList = redisDemo.getList(listKey);
        System.out.println(retrievedList);

        String hashKey = "myHash";
        Map<String, Object> hashValues = new HashMap<>();
        hashValues.put("field1", "value1");
        hashValues.put("field2", "value2");
        hashValues.put("field3", "value3");
        redisDemo.setHash(hashKey, hashValues);

        Map<Object, Object> retrievedHash = redisDemo.getHash(hashKey);
        System.out.println(retrievedHash);

        String setKey = "mySet";
        Set<Object> setValues = new HashSet<>(Arrays.asList("value1", "value2", "value3"));
        redisDemo.setSet(setKey, setValues);

        Set<Object> retrievedSet = redisDemo.getSet(setKey);
        System.out.println(retrievedSet);
    }
}
这是一个更详细的示例,包括了针对具体数据类型的操作方法。你可以根据自己的需求进行修改和扩展。

Tomar una captura de pantalla:

 Análisis de resultados:

Se han agregado los métodos de operación de tres tipos de datos: hash, lista y conjunto. No hay tipos de datos complicados, pero básicamente son suficientes.

Si está interesado, también puede instalar Sider para experimentar la conveniencia que brinda chatgtp. Tiene la capacidad de comprender el contexto, pero también necesitamos indicar las palabras clave y analizar los resultados antes de usarlo. Después de todo, incluso si comunicarse con la gente, es posible que no obtenga una respuesta completamente satisfactoria. Para chatgtp, es posible que también necesite identificar el contenido de la respuesta. Si no está satisfecho con la respuesta, debe continuar planteándola y dejar que ella continúe dando respuestas optimizadas. Por supuesto, también es fundamental aprender a decir las palabras clave.

Luego, como generación de código, al final aún debe usarse en la herramienta de desarrollo, puede conectarlo específicamente y probar la precisión del código generado.

Supongo que te gusta

Origin blog.csdn.net/jiao_zg/article/details/132314450
Recomendado
Clasificación