Java操作Redis

本文介绍了如何使用Java操作Redis,从创建项目开始,逐步讲解了添加依赖、配置文件设置,然后详细阐述了如何通过Redis连接池建立连接,并展示了封装JedisUtil工具类的方法,以便更方便地获取和操作Redis连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java操作Redis

创建项目

创建项目

tdhVoT.png
tdhlO1.png

tdhaSH.png

tdhr0P.png

添加依赖
<?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>2.2.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<groupId>com.xxxx</groupId>
	<artifactId>redisdemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>redisdemo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<!-- spring data redis 组件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
			<!--
                1.x 的版本默认采用的连接池技术是 Jedis,
                2.0 以上版本默认连接池是 Lettuce,
                如果采用 Jedis,需要排除 Lettuce 的依赖。
             -->
			<exclusions>
				<exclusion>
					<groupId>io.lettuce</groupId>
					<artifactId>lettuce-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- jedis 依赖 -->
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</dependency>
		<!-- web 组件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- test 组件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>
配置文件
spring:
  redis:
    # Redis服务器地址
    host: 192.168.10.100
    # Redis服务器端口
    port: 6379
    # Redis服务器密码
    password: root
    # 选择哪个库,默认0库
    database: 0
    # 连接超时时间
    timeout: 10000ms
    jedis:
      pool:
        # 最大连接数,默认8
        max-active: 1024
        # 最大连接阻塞等待时间,单位毫秒,默认-1ms
        max-wait: 10000ms
        # 最大空闲连接,默认8
        max-idle: 200
        # 最小空闲连接,默认0
        min-idle: 5

Java怎么连接Redis?

/**
 * 连接Redis
 */
@Test
public void initConn01() {
    // 创建jedis对象,连接redis服务
    Jedis jedis = new Jedis("192.168.10.100", 6379);

    // 设置认证密码
    jedis.auth("root");

    // 指定数据库 默认是0
    jedis.select(1);

    // 使用ping命令,测试连接是否成功
    String result = jedis.ping();
    System.out.println(result);// 返回PONG

    // 添加一条数据
    jedis.set("username", "zhangsan");

    // 获取一条数据
    String username = jedis.get("username");
    System.out.println(username);

    // 释放资源
    if (jedis != null)
        jedis.close();
}

通过Redis连接池获取连接对象并操作服务器

/**
 * 通过Redis连接池获取连接对象
 */
@Test
public void initConn02() {
    // 初始化redis客户端连接池
    JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "192.168.10.100", 6379, 10000, "root");

    // 从连接池获取连接
    Jedis jedis = jedisPool.getResource();

    // 指定数据库 默认是0
    jedis.select(2);

    // 使用ping命令,测试连接是否成功
    String result = jedis.ping();
    System.out.println(result);// 返回PONG

    // 添加一条数据
    jedis.set("username", "zhangsan");

    // 获取一条数据
    String username = jedis.get("username");
    System.out.println(username);

    // 释放资源
    if (jedis != null)
        jedis.close();
}

封装JedisUtil对外提供连接对象获取方法

@Configuration
public class RedisConfig {
    //服务器地址
    @Value("${spring.redis.host}")
    private String host;
    //端口
    @Value("${spring.redis.port}")
    private int port;
    //密码
    @Value("${spring.redis.password}")
    private String password;
    //超时时间
    @Value("${spring.redis.timeout}")
    private String timeout;
    //最大连接数
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxTotal;
    //最大连接阻塞等待时间
    @Value("${spring.redis.jedis.pool.max-wait}")
    private String maxWaitMillis;
    //最大空闲连接
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
    //最小空闲连接
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;


    @Bean
    public JedisPool redisPoolFactory(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //注意值的转变
  jedisPoolConfig.setMaxWaitMillis(Long.parseLong(maxWaitMillis.substring(0,maxWaitMillis.length()-2)));
        //注意属性名
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, Integer.parseInt(timeout.substring(0,
                timeout.length() - 2)), password);
        return jedisPool;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值