SpringBoot系列——Jedis使用配置详解

SpringBoot系列——Jedis使用配置详解

一、文章概述

本篇文章讲述Java如何配置使用Jedis。Jedis是一个用java写的Redis数据库操作的客户端,通过Jedis,可以很方便的对redis数据库进行操作。
文章书写不易,点个关注不迷路哦,O(∩_∩)O哈哈~

二、准备工作

  • 开发环境
    java 1.8
    springboot2.1.0.RELEASE
    已经安装好Redis(重要)

三、具体实现

1. 导入依赖

导入相关依赖,cache、spring data redis

<!-- redis -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- jedis -->
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.9.0</version>
</dependency>

2. 添加redis配置

在application中添加jedis连接池配置。
Jedis Pool,可以理解为类似jdbc连接池的作用

spring:
  redis:
    host: localhost
    port: 32190
    database: 2
    timeout: 2000
    # jedis配置
    jedis:
      pool:
        max-active: 200
        max-wait: -1
        max-idle: 10
        min-idle: 10

3. 添加JedisPool配置类

添加jedis Pool 连接池配置类

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


@Configuration
@EnableCaching
@Slf4j
public class JedisConfig extends CachingConfigurerSupport (
	
	@Value("spring.redis.host")
	private String host;
	
	@Value("spring.redis.port")
	private int port;
	
	@Value("spring.redis.timeout")
	private int timeout;

	@Value("spring.redis.jedis.pool.max-active")
	private int maxActive;

	@Value("spring.redis.jedis.pool.max-wait")
	private int maxWait;

	@Value("spring.redis.jedis.pool.max-idle")
	private int maxIdle;

	@Value("spring.redis.jedis.pool.min-idle")
	privateint minIdle;

	public JedisPool redisPoolFactory() {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxIdle(maxIdle);
		jedisPoolConfig.setMinIdle(minIdle);
		jedisPoolConfig.setMaxWaitMillis(maxWait);
		jedisPoolConfig.setMaxTotal(maxActive);
		JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, null);
		log.info("注册ReidsPool成功:redis地址 {} ,端口号 {} ", host, port);
		return jedisPool;	
	}
)

4. Jedis工具类

开发中,最好将Jedis的相关操作,封装为一个工具类,使用时,直接注入即可。

/**
 * Jedis工具类:以String类型为例,封装部分方法
 */
@Component
public class JedisUtils {
	
	@Autowired
	private JedisPool jedisPool;

	private Jedis jedis = null;

	/**
 	 * 获取一个Jedis实例
 	 */
	public Jedis getInstance() {
		jedis = jedisPool.getResource();
		jedis.select(1); // 选择存储库,单机版默认为db(0)
		return jedis;
	}

	/**
 	 * 回收Jedis实例
 	 */
	public void takebackJedis(Jedis jedis) {
		if (jedis != null && jedisPool != null) {
			jedsi.close();
		}	
	}

	/**
 	 * 根据key获取Value
 	 */
	public String get(String key) {
		return jedis.get(key);	
	}

	/**
 	 * 添加键值对
 	 */
	public String set(String key, String value) {
		// jedie.set(key, value, "NX", "EX", 1800); // 添加key设置TTL
		return jedis.set(key, value);	
	}

	/**
 	 * 删除一个或多个key
 	 */
	public Long del(String... keys) {
		return jedis.del(keys);	
	}

	/**
 	 * java对象序列化后存入redis
 	 */
	public byte[] objectSerialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			return baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (oos != null) {
					oos.close();
				}
				if (baos != null) {
					baos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
 	 * byte反序列化为java对象
 	 */
	public Object deObjectSerialize(byte[] bytes) {
		ObjectIutputStream ois = null;
		ByteArrayIutputStream bais = null;
		try {
			bais = new ByteArrayIutputStream(bytes);
			ois = new ObjectIutputStream(bais);
			return ois.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (ois != null) {
					ois.close();
				}
				if (bais != null) {
					bais.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}

5. 使用工具类

直接在代码中注入即可实现对Redis的操作

@Autowired
private JedisUtils jedisUtils;

public static void main(String[] args) {
	// 获取jedis实例
	Jedis jedis = jedisUtils.getInstance();
	// 具体操作
	jedisUtils.set("name", "张三");
	jedisUtils.get("name");
	jedisUtils.del("name");
	// 回收Jedis
	jedisUtils.takebackJedis(jedis);
}

其他redis操作自行选择封装即可,如有其他好想法,欢迎评论区交流。

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值