jedis采用key,value的形式保存数据,使用nosql
sql和nosql的区别
一:入门案例
导入依赖
<dependencies><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>3.7.0</version></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>5.10.5</version><scope>compile</scope></dependency></dependencies>
连接ip地址,端口号和密码,选择数据库
jedis = new Jedis("127.0.0.1",6379);
jedis.select(0);
执行操作
@Testvoid testString(){jedis.set("name","zhangsan");String name = jedis.get("name");System.out.println(name);}@Testvoid testHash(){jedis.hset("user:1","age","18");String name = jedis.hget("user:1", "age");Map<String, String> stringStringMap = jedis.hgetAll("user:1");System.out.println(stringStringMap);System.out.println(name);}
关闭
@AfterEachvoid tearDown(){jedis.close();}
二:使用连接池
由于我的redis没有设置密码,所以在配置参数时少了一个密码参数
package com.jedis;import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;public class jedisConnectionFactory {private static JedisPool jedisPool;static {//配置连接池JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();//最大连接数jedisPoolConfig.setMaxTotal(8);//最大空闲连接数jedisPoolConfig.setMaxIdle(8);//最小空闲连接数jedisPoolConfig.setMinIdle(0);//最大等待时间jedisPoolConfig.setMaxWaitMillis(1000);//创建连接池对象jedisPool = new JedisPool(jedisPoolConfig,"127.0.0.1",6379,1000);}public static Jedis getJedis(){return jedisPool.getResource();}
}
回到测试代码中,setup方法直接使用连接池获取redis
jedis=jedisConnectionFactory.getJedis();jedis.select(0);
三:SpringDataRedis
SpringDataRedis提供了RedisTemplate工具类,封装了对redis的操作,并且把不同数据类型的操作API封装到了不同的类型中(返回值类型都是operations对象):
导入依赖
<?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>3.3.5</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.redis</groupId><artifactId>SpringDataRedis</artifactId><version>0.0.1-SNAPSHOT</version><name>SpringDataRedis</name><description>SpringDataRedis</description><url/><licenses><license/></licenses><developers><developer/></developers><scm><connection/><developerConnection/><tag/><url/></scm><properties><java.version>17</java.version></properties><!--redis依赖--><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--连接池依赖--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>
配置yml文件
在spring中默认使用lettuce,如果使用jedis需要在pom中导入依赖
spring:data:redis:host: 127.0.0.1port: 6379password:lettuce:pool:max-active: 8max-idle: 8min-idle: 0max-wait: 100ms
注入,自动装配,测试
package com.redis;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;@SpringBootTest
class SpringDataRedisApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid testString() {redisTemplate.opsForValue().set("name","flt");Object o = redisTemplate.opsForValue().get("name");System.out.println(o);}}
得出结果
因为redisTemplate中有默认的序列化工具(默认为jdk序列化ObjectOutputstream)
这样会导致数据难以读取,并且更加占用内存,这时候就可以使用自定义序列化方式
package com.redis.redis.config;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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){// 1.创建RedisTemplate对象RedisTemplate<String, Object> template = new RedisTemplate<>();// 2.设置连接工厂对象template.setConnectionFactory(connectionFactory);//创建json序列化工具GenericJackson2JsonRedisSerializer jasonRedisSerializer = new GenericJackson2JsonRedisSerializer();// 设置Key的序列化器template.setKeySerializer(RedisSerializer.string());template.setHashKeySerializer(RedisSerializer.string());// 设置Value的序列化器template.setValueSerializer(jasonRedisSerializer);template.setHashValueSerializer(jasonRedisSerializer);return template;}
}
使用boot程序测试
package com.redis;import com.redis.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.ObjectError;@SpringBootTest
class SpringDataRedisApplicationTests {@Autowiredprivate RedisTemplate<String , Object> redisTemplate;@Testvoid testString() {redisTemplate.opsForValue().set("name","小王");Object o = redisTemplate.opsForValue().get("name");System.out.println(o);}@Testvoid testSaveUser(){redisTemplate.opsForValue().set("user:100",new User("李白",18));Object o = redisTemplate.opsForValue().get("user:100");System.out.println(o);}
}
测试结果
使用StringRedisTemplate节省内存空间,但是需要手动的序列化和反序列化
package com.redis;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.redis.pojo.User;
import org.junit.jupiter.api.Test;
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;@SpringBootTest
class RedisStringTest {@Autowiredprivate StringRedisTemplate stringRedisTemplate;@Testvoid testString() {stringRedisTemplate.opsForValue().set("name","小王");Object o = stringRedisTemplate.opsForValue().get("name");System.out.println(o);}// json序列化private static final ObjectMapper mapper = new ObjectMapper();@Testvoid testSaveUser() throws JsonProcessingException {User user = new User("李白",18);String s = mapper.writeValueAsString(user);stringRedisTemplate.opsForValue().set("user:200",s);String jsonUser = stringRedisTemplate.opsForValue().get("user:200");//手动反序列化User user1 = mapper.readValue(jsonUser, User.class);System.out.println(user1);}
}
创建hash数据
@Testvoid testHash(){stringRedisTemplate.opsForHash().put("user:300","name","小王");stringRedisTemplate.opsForHash().put("user:300","age","18");Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("user:300");System.out.println(entries);}