Jedis与SpringDataRedis的配置及使用

在java中操作Redis

Jedis

Jedis的maven坐标

<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency> 
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.8.0</version>
</dependency>
@Test
public void testRedis(){
    //1.获取链接
    Jedis jedis=new Jedis("localhost",6379);

    //有密码的话
    //jedis.auth("20020630");
    //2.执行具体的操作
        jedis.set("username","xiaoming");//设置
        jedis.del("username");//删除
        
        jedis.hset("myhash","addr","beijin");//存放hash类型的
        jedis.hget("myhash","addr");//获取
        
        jedis.keys("*");//获取所有的key
    //3.关闭连接
    jedis.close();
}

Jedis的连接池

package com.heima.jedis.util;

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

/**
 * @ClassName JedisConnectionFactory
 * @Author ylh
 * @Date 2022/12/24 21:30
 * @Description
 */

public class JedisConnectionFactory
{
    private static final JedisPool jedisPool;

    static {
        //配置连接池
        JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(8);
        jedisPoolConfig.setMaxIdle(8);
        jedisPoolConfig.setMinIdle(0);//最小空闲连接
        jedisPoolConfig.setMaxWaitMillis(1000);
        
        jedisPool=new JedisPool(jedisPoolConfig,"192.168.205.128",6379,1000,"20020630");
        
    }
    
    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
}

Spring Data Redis

准备一个spring boot项目

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>

        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-pool2artifactId>
        dependency>

配置文件

spring:
  application:
    name: Redis

    #redis相关配置
redis:
  host: localhost
  port: 6379
  #password: 20020630
  database: 0  #0号数据库
  lettuce: #如果要配置Jedis的需要额外导入
  #Redis连接池配置
  pool:
    max-active: 8  #最大连接数
    max-wait: 1ms  #连接池中的最大阻塞等待时间
    max-idle: 4    #连接池中的最大空闲链接
    min-idle: 0    #连接池中的最小空闲链接

Redis服务默认提供了16个数据库

使用select 1/2/3...切换

Spring Data Redis 中提供了一个高度封装的类:RedisTemplate,针对jedis客户端中大量的api进行了归类封装,将同一类型操作封装为operation接口,具体分类如下

ValueOperations :简单的K-V操作

SetOperations:set数据类型的操作

ZSetOperations:zset类型的数据操作

HashOperations:针对map类型的数据操作

ListOperations:针对list类型的数据操作

在测试类中

@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringDataRedisTest {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testString(){
        redisTemplate.opsForValue().set("city","beijin");

    }
}

image-20220808153301792

需要修改默认的序列化方式
引入依赖

    
        com.fasterxml.jackson.core
        jackson-databind
    
@Configuration
public class RedisConfig {

    @Bean
    RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory){
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //设置链接工厂
        template.setConnectionFactory(connectionFactory);
        //创建JSON的序列化工具
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();

        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());

        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }
}

也可以直接使用StringRedisTemplate
写入Reids时,手动把对象序列化为JSON
读取Redis时,手动把读取到的JSON反序列化为对象

五种类型的具体操作

@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringDataRedisTest {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testString(){
       //redisTemplate.opsForValue().set("city","beijin");
        Object city = redisTemplate.opsForValue().get("city");
        //设置超时时间10s
        redisTemplate.opsForValue().set("key1","value1",10l, TimeUnit.SECONDS);
        System.out.println(city);

    }

    //操作hash类型的数据
    @Test
    public void testHash(){
        HashOperations hashOperations = redisTemplate.opsForHash();
        //存值
        hashOperations.put("002","name","zhangsan");
        hashOperations.put("002","age","20");
        //取值
        Object name = hashOperations.get("002", "name");
        System.out.println(name);

        //获取hash结构中的所有字段
        Set keys = hashOperations.keys("002");
        for (Object key : keys) {
            System.out.println(key);
        }

        //获取hash结构中的所有值
        List values = hashOperations.values("002");
        for (Object value : values) {
            System.out.println(value);
        }
    }
    //操作List类型的数据
    @Test
    public void testList(){
        ListOperations listOperations = redisTemplate.opsForList();


        //存值
        listOperations.leftPush("mylist","a");
        listOperations.leftPushAll("mylist","b","c");
        //取值
        List<String> mylist = listOperations.range("mylist", 0, -1);
        for (String s : mylist) {
            System.out.println(s);
        }

        //出队列
        //获得列表的长度
        Long mylistLengthist = listOperations.size("mylist");
        int mylistLength = mylistLengthist.intValue();
        for (int i = 0; i < mylistLength; i++) {
            System.out.println( listOperations.rightPop("mylist"));

        }

    }


    //操作set集合的数据
    @Test
    public void testSet(){
        SetOperations setOperations = redisTemplate.opsForSet();

        //存值
        setOperations.add("myset","a","b","c","a");


        //取值
        Set<String> myset = setOperations.members("myset");
        for (String s : myset) {
            System.out.println(s);
        }

        System.out.println("----------------");
        //删除
        setOperations.remove("myset","b");

        Set<String> myset1 = setOperations.members("myset");
        for (String s : myset1) {
            System.out.println(s);
        }

    }

    //ZSET有序集合
    @Test
    public void testZset(){
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();

        //存值
        zSetOperations.add("myZset","a",10.0);
        zSetOperations.add("myZset","b",8.0);
        zSetOperations.add("myZset","c",9.0);
        zSetOperations.add("myZset","c",9.0);
        //后来的会覆盖之前相同的元素

        //取值

        Set<String> myZset = zSetOperations.range("myZset", 0, -1);

        for (String s : myZset) {
            System.out.println(s);
        }
        //修改分数
        zSetOperations.incrementScore("myZset","b",20.0);

        //删除成员
        zSetOperations.remove("myZset","c");

        System.out.println("--------------------");
        Set<String> myZset1 = zSetOperations.range("myZset", 0, -1);

        for (String s : myZset1) {
            System.out.println(s);
        }

    }

    //通用操作
    @Test
    public void testCommon(){
        //获取Redis中的所有的key

        Set<String> keys = redisTemplate.keys("*");
        for (String key : keys) {
            System.out.println(key);
        }
        //判断某个key是否存在
        Boolean itcast = redisTemplate.hasKey("itcast");
        System.out.println(itcast);

        //删除指定key
        redisTemplate.delete("myZset");

        //获取指定key对应的value类型
        DataType myset = redisTemplate.type("myset");
        System.out.println(myset);

    }
}

你可能感兴趣的:(Redis,java,redis,开发语言)