在Java中操作Redis

使用Jedis操作Redis

redis的java客户端很多,官方推荐的有三种:

Jedis

Lettuce

Redisson

Spring 对Redis 客户端进行了整合,提供了Spring Date Redis ,在Spring Boot项目中还提供了对应的Starter,即spring-boot-starter-data-redis

使用Jedis操作Redis的步骤

1.获取链接

2.执行操作

3.关闭连接

package com.example.demotest;

import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;

import java.util.Set;

/**
 * 使用Jedis操作Redis
 */
public class JedisTest {

    @Test
    public void testRedis(){
        //1.获取连接
        Jedis jedis = new Jedis("localhost",6379);

        //2.执行具体的操作
        jedis.set("username","huan");
        String username = jedis.get("username");
        System.out.println(username);

        //jedis.del("username");
        jedis.hset("myhash","addr","sz");
        String hValue = jedis.hget("myhash", "addr");
        System.out.println(hValue);

        Set keys = jedis.keys("*");
        for (String key : keys) {
            System.out.println(key);
        }
        //3.关闭连接
        jedis.close();
    }
}

在Java中操作Redis_第1张图片

使用Spring Data Redis来简化Redis操作

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

ValueOperations:简单K-V操作

SetOperations :set 类型数据操作

ZSetOperations:zset 类型数据操作

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

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

默认操作的是0号数据库,也可以切换其他数据库

在Java中操作Redis_第2张图片

设置一下序列化,这样设置key的时候不会变成乱码

package com.example.demotest;

import org.springframework.cache.annotation.CachingConfigurerSupport;
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.StringRedisSerializer;
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory){

        RedisTemplate redisTemplate = new RedisTemplate<>();

        redisTemplate.setKeySerializer(new StringRedisSerializer());

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        redisTemplate.setConnectionFactory(connectionFactory);
        return  redisTemplate;
    }
}

package com.example.demotest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.*;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringDataRedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testString(){
        redisTemplate.opsForValue().set("city2","sz");
        String city2 = (String) redisTemplate.opsForValue().get("city2");
        System.out.println("打印一下" + city2);
        //指定过期时间 10 秒
        redisTemplate.opsForValue().set("key1","value1",10l, TimeUnit.SECONDS);
        //如果不存在key则设置
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("city", "sz");
        System.out.println(aBoolean);

    }

    @Test
    public void testHash(){
        HashOperations hashOperations = redisTemplate.opsForHash();
        //存值
        hashOperations.put("002","name","hh");
        hashOperations.put("002","age","20");
        hashOperations.put("002","address","sz");
        //取值
        String age = (String) hashOperations.get("002", "age");
        System.out.println(age);

        //获得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","d");

        //取值
        List mylist = listOperations.range("mylist", 0, -1);
        for (String value : mylist) {
            System.out.println(value);
        }

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


    }

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

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

        //取值
        Set myset = setOperations.members("myset");
        for (String s : myset) {
            System.out.println(s);
        }
        //删除成员
        setOperations.remove("myset","a","b");

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

    }

    /**
     * 操作zset类型的数据
     */
    @Test
    public void testZset(){
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();

        //存值
        zSetOperations.add("myZset","a",10.0);
        zSetOperations.add("myZset","b",11.0);
        zSetOperations.add("myZset","d",12.0);
        zSetOperations.add("myZset","a",13.0);

        //取值
        Set myZset = zSetOperations.range("myZset", 0, -1);
        for (String s : myZset) {
            System.out.println(s);
        }
        //修改分数
        zSetOperations.incrementScore("myZset","b",20.0);

        //取值
        myZset = zSetOperations.range("myZset", 0, -1);
        for (String s : myZset) {
            System.out.println(s);
        }
        //删除成员
        zSetOperations.remove("myZset","a","b");


    }

    @Test
    public void testCommon(){
        //获取Redis 中所有的key
        Set keys = redisTemplate.keys("*");
        for (String key : keys) {
            System.out.println(key);
        }

        //判断某个key是否存在
        Boolean hh = redisTemplate.hasKey("hh");
        System.out.println(hh);

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

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

    }
}

在Java中操作Redis_第3张图片

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