Java操作Redis的5种常见方法

Redis的客户端操作有以下几种方式:

jedis、redisson、lettuce、Redistemplate、jedisPool

1、jedis

jedis是Redis官方推荐的客户端,jedis是由socket实现的,它是同步的,所以一般需要自己实现连接池使用为佳。也可以使用apache的jedispool。
jedis相对来说更加的原生,只支持基本的数据类型如:

StringHashListSetSorted Set

Java实现操作redis

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

操作:

import redis.clients.jedis.Jedis;

public class JedisDemo {
    public static void main(String[] args) {
        String host = "localhost";
        int port = 6379;
        Jedis jedis = new Jedis(host, port);

        jedis.set("key", "value");
        String value = jedis.get("key");
        System.out.println("Value is " + value);
    }
}

2、redisson

redisson底层是netty实现,因此它是异步非阻塞,相对于jedis来说,redisson对结果有更多的包装,更加抽象,让开发者只关注于业务。
redisson对分布式的支持是它的一大亮点。
redisson支持的数据结构有:

List, Set, Map, Queue, SortedSet, ConcureentMap, Lock,
 AtomicLong, CountDownLatch

Java实现操作redis

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.15.5</version>
</dependency>

操作:

Config config = new Config();
config.useSingleServer().setAddress("redis://localhost:6379");
 
RedissonClient redisson = Redisson.create(config);
// 获取字符串
RBucket<String> bucket = redisson.getBucket("myKey");
String value = bucket.get();
 
// 设置字符串
bucket.set("myValue");
 
// 获取Map
RMap<String, String> map = redisson.getMap("myMap");
String mapValue = map.get("myMapKey");
 
// 设置Map
map.put("myMapKey", "myMapValue");

3、lettuce

lettuce也是netty实现,也是异步非阻塞的。

<dependency>
 <groupId>io.lettuce</groupId>
 <artifactId>lettuce-core</artifactId>
 <version>6.2.5.RELEASE</version>
</dependency>

常见API

public class LettuceUtil {
 
    public static void main(String[] args) {
        RedisURI redisUri = RedisURI.builder()
                .withHost("127.0.0.1").withPort(6379).withPassword("111111")
                .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                .build();
        RedisClient redisClient = RedisClient.create(redisUri);
        StatefulRedisConnection<String, String> connection = redisClient.connect();
        //获取同步操作命令工具
        RedisCommands<String, String> commands = connection.sync();
 
        System.out.println("清空数据:"+commands.flushdb());
        System.out.println("判断某个键是否存在:"+commands.exists("username"));
        System.out.println("新增<'username','xmr'>的键值对:"+commands.set("username", "xmr"));
        System.out.println("新增<'password','password'>的键值对:"+commands.set("password", "123"));
        System.out.println("获取<'password'>键的值:"+commands.get("password"));
        System.out.println("系统中所有的键如下:" + commands.keys("*"));
        System.out.println("删除键password:"+commands.del("password"));
        System.out.println("判断键password是否存在:"+commands.exists("password"));
        System.out.println("设置键username的过期时间为5s:"+commands.expire("username", 5L));
        System.out.println("查看键username的剩余生存时间:"+commands.ttl("username"));
        System.out.println("移除键username的生存时间:"+commands.persist("username"));
        System.out.println("查看键username的剩余生存时间:"+commands.ttl("username"));
        System.out.println("查看键username所存储的值的类型:"+commands.type("username"));
 
        connection.close();
        redisClient.shutdown();
    }
}

4、JedisPool

由于jedis是同步的,因此用jedisPool连接池。

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.7.0</version>
</dependency>

使用示例:

public class JedisConnectionFactory {
 
    private final static JedisPool jedisPool;
 
    static {
        //配置连接池
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //最大连接
        jedisPoolConfig.setMaxTotal(8);
        //最大空闲连接
        jedisPoolConfig.setMaxIdle(8);
        //最小空闲连接
        jedisPoolConfig.setMinIdle(0);
        //最长等待时间,ms
        jedisPoolConfig.setMaxWaitMillis(200);
        jedisPool = new JedisPool(jedisPoolConfig,
                "localhost",6379,1000,"123");
    }
 
    //获取jedis对象
    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
}
 
 
 
 
@SpringBootTest
class ProjectApplicationTests {
 
    //引入jedis
    private Jedis jedis;
 
    @BeforeEach
    void setUp() {
        //建立连接,host是自己的redis服务地址,port是端口号
        jedis = JedisConnectionFactory.getJedis();
        //设置密码
        jedis.auth("123456");
        // 选择库
        jedis.select(0);
    }
 
    @Test
    void testString() {
        // 存入数据
        String result = jedis.set("name", "小郑");
        System.out.println("result = " + result);
        // 获取数据
        String name = jedis.get("name");
        System.out.println("name = " + name);
    }
 
    @Test
    void testHash() {
        //插入hash数据
        jedis.hset("user:1","name","小郑");
        jedis.hset("user:1","age","24");
 
        //获取所有hash数据并输出
        Map<String, String> stringStringMap = jedis.hgetAll("user:1");
        System.out.println(stringStringMap);
    }
 
    @AfterEach
    void tearDown() {
        if (jedis != null)
            jedis.close();
    }

5、RedisTemplate

RedisTemplate是对jedis和lettuce的封装,springboot2.0之后,默认使用 lettuce,使用时只要配置好属性,就能自动由SpringBoot自动管理连接池。
jedis性能较强,jedis的性能至少是RedisTemplate的3倍以上,jedis结合jedisPool使用既可以有高性能又可以保证redis的连接可控。
在性能要求、并发操作不高的场景建议使用RedisTemplate,在并发高,性能要求高的场景下建议使用jedis。
Java实现

 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

操作:

package test;
 
import com.hs.springbootdemo.SpringbootdemoApplication;
import com.hs.springbootdemo.dao.entity.UserEntity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
 
import javax.annotation.Resource;
 
@RunWith(SpringRunner.class)//SpringBoot 2.X 默认使用Junit4
@SpringBootTest(classes = SpringbootdemoApplication.class)
public class RedisTest {
 
    //如果无法注入RedisTemplate,就使用@Resource试试
    @Autowired
    private StringRedisTemplate stringRedisTemplate;//自带的字符串模板类,用于存储字符串
 
    @Autowired
    private RedisTemplate redisTemplate;//自带的对象模板类,用于存储对象
 
    @Test
    public void test() throws Exception
    {
        // 保存字符串
        stringRedisTemplate.opsForValue().set("username", "redis!!!");
        Logger logger = LoggerFactory.getLogger(RedisTest.class);
        String str = stringRedisTemplate.opsForValue().get("username");
        logger.warn(str);
    }
 
    @Test
    public void test1() throws Exception {
 
        UserEntity user = new UserEntity();
        user.setUsername("hello");
        user.setPassword("12345");
 
        redisTemplate.opsForValue().set("user_1", user);
        UserEntity user1 = (UserEntity) redisTemplate.opsForValue().get("user_1");
 
        System.out.println(user1.getUsername());
    }
}

总结

Jedis性能好,适合高性能场景,不过要用JedisPool,如果对性能要求不高,或者在SpringBoot项目中使用RedisTemplate是不错的。

  • 19
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值