Redis-Jedis连接池\RedisTemplate\StringRedisTemplate

1. Jedis连接池

1.1 通过工具类

1.1.1 连接池:JedisConnectionFactory:

package com.fst.jedis.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisConnectionFactory {
    private static final JedisPool jedispool;
    static {
        //配置连接池
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(8);//连接数,最多只允许创建8个
        poolConfig.setMaxIdle(8);//最大空闲连接数
        poolConfig.setMinIdle(0);//释放到0为止
        poolConfig.setMaxWaitMillis(1000);//当连接池里,没有连接可以用的时候,我们等多少时间,默认值为-1(一直等等到有连接),这里设置1000毫秒
        //创建连接池对象
        jedispool=new JedisPool(poolConfig,"192.168.88.128",6379,1000,"123456");
    }
    public static Jedis getJedisPool(){

        return jedispool.getResource();
    }
}

1.1.2 test:(代码其实只有连接池那里改变了)

package com.fst.test;
import com.fst.jedis.util.JedisConnectionFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;
import java.util.Map;
public class JedisTest {
    private Jedis jedis; //创建一个jedis对象
    @BeforeEach //初始化方法
    void setUp() {
        //jedis=new Jedis("192.168.88.128",6379);//地址和端口号,没有连接池的时候才需要使用这个
        jedis= JedisConnectionFactory.getJedisPool();
        jedis.auth("123456");//密码
        jedis.select(0);//哪个库
    }

    @Test
    void testString() {
        String result = jedis.set("name", "涛哥");//String类型,创建
        System.out.println("result="+result);
        String name = jedis.get("name");//得到值
        System.out.println("name="+name);
    }
    @Test
    void testHash(){
        //插入hash
        jedis.hset("user:1","name","涛哥");//Hash类型,创建
        jedis.hset("user:1","age","21");//Hash类型,创建
        Map<String, String> map = jedis.hgetAll("user:1"); //讲得到的Hash用Map封装起来

        System.out.println("map="+map);//打印map
    }
    @AfterEach
    void tearDown() {
        if (jedis != null){
            jedis.close();//底层源码里:没有连接池释放缓存,有连接池则是归还
        }
    }

}

2. SpringDataRedis(lettuce)

2.1 新建一个springboot项目:

在这里插入图片描述
在这里插入图片描述

2.2 pom:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://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>3.3.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.fst</groupId>
    <artifactId>redis-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>redis-demo</name>
    <description>redis-demo</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>21</java.version>
    </properties>
    <dependencies>
<!--  redis依赖      -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
<!--  common-pool 连接池-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
<!--  Jackson依赖,用来支持我们配置文件里面的序列化转为json-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2.3 application.yaml:

spring:
  data:
    redis:
      host: 192.168.88.128
      port: 6379
      password: 123456
      lettuce:
        pool:
          max-active: 8
          max-idle: 8
          min-idle: 0
          max-wait: 1000ms

2.4 Test

package com.fst;

import com.fst.redis.pojo.User;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
class RedisDemoApplicationTests {
    @Resource
    private RedisTemplate redisTemplate;//注入RedisTemplate依赖

    @Test
    void testString() {
        //写入一条String数据
        redisTemplate.opsForValue().set("name","涛哥");
        //获取String数据
        Object name = redisTemplate.opsForValue().get("name");
        System.out.println("name="+name);
    }
    }

3 为什么要使用StringRedisTemplate?

因为我们使用RedisTemplate的时候他写入redis中的是
在这里插入图片描述
因为序列化到redis的时候,是以二进制的形式存储的,所以需要将对象序列化,才能存储到redis中,和redis的值保持一致。

3.1 进行序列化配置:

3.1.1 创建配置类RedisConfig :

package com.fst.redis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
//因为序列化到redis的时候,是以二进制的形式存储的,所以需要将对象序列化,才能存储到redis中,和redis的值保持一致
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory){//连接工厂由springboot创建
        //创建RedisTemplate 对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //设置连接工厂
        template.setConnectionFactory(connectionFactory);
        //创建JSON序列化工具
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        //设置key的序列化
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        //设置Value的序列化
        template.setValueSerializer(jsonRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);
        //返回
        return template;
    }
}

3.1.2 修改Test:

package com.fst;

import com.fst.redis.pojo.User;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
class RedisDemoApplicationTests {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;//注入redisTemplate的依赖
    //并且,还需要指定<String,Object>。

    @Test
    void testString() {
        //写入一条String数据
        redisTemplate.opsForValue().set("name","涛哥");
        //获取String数据
        Object name = redisTemplate.opsForValue().get("name");
        System.out.println("name="+name);
    }
    }

3.1.3 存储对象

新建User类:

package com.fst.redis.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String name;
    private int age;
}

test:

package com.fst;

import com.fst.redis.pojo.User;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
class RedisDemoApplicationTests {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;//注入redisTemplate的依赖

    @Test
    void testString() {
        //写入一条String数据
        redisTemplate.opsForValue().set("name","涛哥");
        //获取String数据
        Object name = redisTemplate.opsForValue().get("name");
        System.out.println("name="+name);
    }
    @Test
    void testSaveUser(){
        //写入数据
        redisTemplate.opsForValue().set("user:100",new User("涛哥",18));
        //获取数据
        User o = (User) redisTemplate.opsForValue().get("user:100");
        System.out.println("o="+o);
    }

}

在这里插入图片描述

4 StringRedisTemplate

4.1 问题

在这里插入图片描述

4.2 重新测试,使用StringRedisTemplate:

(别忘了在pom中引入我们的json依赖),mapper工具类,可以学习

package com.fst;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fst.redis.pojo.User;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.runtime.ObjectMethods;
import java.util.Map;

@SpringBootTest
class RedisStringTests {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Test
    void testString() {
        //写入一条String数据
        stringRedisTemplate.opsForValue().set("name","涛哥");
        //获取String数据
        Object name = stringRedisTemplate.opsForValue().get("name");
        System.out.println("name="+name);
    }
    private static  final ObjectMapper mapper =new ObjectMapper();

    @Test
    void testSaveUser() throws JsonProcessingException {
        //创建对象
        User user = new User("涛哥",18);
        //手动序列化
        String json = mapper.writeValueAsString(user);
        //写入数据
        stringRedisTemplate.opsForValue().set("user:200",json);
        //获取数据
       String jsonUser =  stringRedisTemplate.opsForValue().get("user:200");
       //手动反序列化
           User user1 = mapper.readValue(jsonUser, User.class);
        System.out.println("user1="+user1);
    }
    @Test
    void testHash(){
        stringRedisTemplate.opsForHash().put("user:400","name","涛哥");
        stringRedisTemplate.opsForHash().put("user:400","age","20");

        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("user:400");
        System.out.println("entries="+entries);

    }
}

在这里插入图片描述

4.3 RedisTemplate 操作Hash

package com.fst;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fst.redis.pojo.User;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.runtime.ObjectMethods;
import java.util.Map;

@SpringBootTest
class RedisStringTests {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Test
    void testString() {
        //写入一条String数据
        stringRedisTemplate.opsForValue().set("name","涛哥");
        //获取String数据
        Object name = stringRedisTemplate.opsForValue().get("name");
        System.out.println("name="+name);
    }
    private static  final ObjectMapper mapper =new ObjectMapper();

    @Test
    void testSaveUser() throws JsonProcessingException {
        //创建对象
        User user = new User("涛哥",18);
        //手动序列化
        String json = mapper.writeValueAsString(user);
        //写入数据
        stringRedisTemplate.opsForValue().set("user:200",json);
        //获取数据
       String jsonUser =  stringRedisTemplate.opsForValue().get("user:200");
       //手动反序列化
           User user1 = mapper.readValue(jsonUser, User.class);
        System.out.println("user1="+user1);
    }
    @Test
    void testHash(){
        stringRedisTemplate.opsForHash().put("user:400","name","涛哥");
        stringRedisTemplate.opsForHash().put("user:400","age","20");

        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("user:400");
        System.out.println("entries="+entries);

    }
}

在这里插入图片描述

相关推荐

  1. RedisTemplateStringRedisTemplate区别

    2024-07-10 19:32:04       18 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 19:32:04       5 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 19:32:04       5 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 19:32:04       4 阅读
  4. Python语言-面向对象

    2024-07-10 19:32:04       7 阅读

热门阅读

  1. 【大模型】解锁语言模型潜能:提示工程的艺术

    2024-07-10 19:32:04       10 阅读
  2. docker run enteypoint怎么样使用呢?

    2024-07-10 19:32:04       8 阅读
  3. kafka中

    kafka中

    2024-07-10 19:32:04      10 阅读
  4. 探索Vue.js:构建高效前端应用的现代框架

    2024-07-10 19:32:04       6 阅读
  5. ffmpeg 获取视频时长的命令及其输出

    2024-07-10 19:32:04       10 阅读
  6. 使用Python绘制甘特图

    2024-07-10 19:32:04       12 阅读
  7. uboot spi nor flash初始化相关的阅读分析(一)

    2024-07-10 19:32:04       10 阅读
  8. 最小生成树(算法篇)

    2024-07-10 19:32:04       10 阅读
  9. K8S集群应用国产信创适配实战经验总结

    2024-07-10 19:32:04       8 阅读
  10. 方程与不等式

    2024-07-10 19:32:04       12 阅读
  11. 力扣1472.设计浏览器历史记录

    2024-07-10 19:32:04       12 阅读
  12. ArcGIS Pro SDK (八)地理数据库 3 数据

    2024-07-10 19:32:04       12 阅读
  13. C语言 找出一个二维数组中的鞍点

    2024-07-10 19:32:04       10 阅读
  14. [目标检测]labelme标注数据转yoloV8需要的.txt格式

    2024-07-10 19:32:04       10 阅读
  15. ES6 之 Promise 构造函数知识点总结 (四)

    2024-07-10 19:32:04       12 阅读