一篇文章带你了解NoSql数据库——Redis简单入门( 四 )

  1. 我们直接在测试类里书写代码
package com.itheima.test;import org.junit.Test;import redis.clients.jedis.Jedis;import java.util.Set;/** * 使用Jedis操作Redis * 我们大致分为三步:获得连接,执行具体操作,关闭连接 */public class JedisTest {    @Test    public void testRedis(){        //1 获取连接(ip或者主机,端口号)        Jedis jedis = new Jedis("localhost",6379);        //2 执行具体的操作(指令基本和redis相同)        jedis.set("username","xiaoming");        String value = jedis.get("username");        System.out.println(value);        jedis.del("username");        jedis.hset("myhash","addr","bj");        String hValue = jedis.hget("myhash", "addr");        System.out.println(hValue);        Set<String> keys = jedis.keys("*");        for (String key : keys) {            System.out.println(key);        }        //3 关闭连接        jedis.close();    }}Spring Data RedisSpring为我们提供了Spring Data Redis,SDR使用在我们的SpringBoot项目中
Spring Data Redis提供了一个高度封装的类:RedisTemplate,针对jedis客户端中大量api进行了归类封装,将同一类操作进行封装
大致分为了以下五种分类:
  • ValueOperations:简单K-V操作
  • SetOperations:set类型数据操作
  • ZSetOperations:zset类型数据操作
  • HashOperations:针对map类型的数据操作
  • ListOperations:针对list类型的数据操作
下面我们来了解其具体使用:
  1. 载入坐标
<?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 http://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.4.5</version>        <relativePath/>    </parent>    <groupId>com.itheima</groupId>    <artifactId>springdataredis_demo</artifactId>    <version>1.0-SNAPSHOT</version>    <properties>        <java.version>1.8</java.version>    </properties>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>        </dependency>        <!--Spring Data Redis坐标-->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-redis</artifactId>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>                <version>2.4.5</version>            </plugin>        </plugins>    </build></project>

经验总结扩展阅读