1.连接redis的三种方法
默认有三种方式连接redis.
第一种:jedis—传统的项目–ssm
第二种:lettuce:---->刚出现没有多久就被springboot整合进来。
第三种:springboot连接redis
1.1 jedis操作redis服务器
1)引入jedis依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.3.1</version>
</dependency>
(2)编写相关的代码
@Test
public void test01(){
Jedis jedis = new Jedis("192.168.1.100",6379);
jedis.flushDB();
jedis.set("k1", "v1");
String k1 = jedis.get("k1");
System.out.println(k1);
jedis.lpush("k2", "zzz", "666", "zyx");
List<String> k11 = jedis.lrange("k2", 0, -1);
System.out.println(k11);
Map<String,String> map=new HashMap<>();
map.put("name","justin");
map.put("age","26");
map.put("occupation","歌手");
jedis.hset("k3",map);
System.out.println(jedis.hgetAll("k3"));
}
每次使用jedis对象时 都需要自己创建,当使用完后,需要关闭该对象。===>jedis中也存在连接池.
1.2 jedis连接池的使用
@Test
public void testPool(){
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(10);//最多的连接个数
config.setMaxTotal(10);//最多空闲的连接个数
config.setMinIdle(2);//最小的空闲个数
config.setTestOnBorrow(true);//获取连接对象时是否验证该对象的连通性
//创建连接池对象
JedisPool jedisPool =new JedisPool(config,"192.168.1.100",6379);
Jedis jedis = jedisPool.getResource();
jedis.flushDB();
String set = jedis.set("k1","v1");
String k1 = jedis.get("k1");
System.out.println(k1);
jedis.lpush("k2","zzz","zyx","zy");
List<String> k2 = jedis.lrange("k2", 0, -1);
System.out.println(k2);
jedis.close();
}
1.3测试jedis使用和不使用连接池的效率
@Test
public void test02(){
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
Jedis jedis=new Jedis("192.168.1.100",6379);
String ping = jedis.ping();
jedis.close();
}
long end = System.currentTimeMillis();
System.out.println("耗时:"+(end-start));
}
@Test
public void test03(){
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(10);//最多的连接个数
config.setMaxTotal(10);//最多空闲的连接个数
config.setMinIdle(2);//最小的空闲个数
config.setTestOnBorrow(true);
JedisPool jedisPool=new JedisPool(config,"192.168.1.100",6379);
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
Jedis jedis = jedisPool.getResource();
String ping = jedis.ping();
jedis.close();
}
long end = System.currentTimeMillis();
System.out.println("耗时"+(end-start));
}
1.4 springboot整合redis
1)添加相关依赖
<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>
修改配置文件
spring.redis.host=192.168.1.100
spring.redis.port=6379
#最多获取数
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
@SpringBootTest
class Redis2ApplicationTests {
@Autowired
private StringRedisTemplate redisTemplate;
@Test
public void test01(){
ValueOperations<String,String> forValue=redisTemplate.opsForValue();
/* forValue.set("k1","zy");
String k1 = forValue.get("k1");
System.out.println(k1);*/
HashOperations<String,Object,Object> forHash=redisTemplate.opsForHash();
/* forHash.put("k2","name","zyx");
forHash.put("k2","age","16");
forHash.put("k2","sex","男");
Map<String,String> map=new HashMap<>();
map.put("name","zy");
map.put("age","17");
map.put("sex","女");
forHash.putAll("k3",map);*/
System.out.println(forHash.keys("k2"));
System.out.println(forHash.values("k3"));
System.out.println(forHash.entries("k2"));
ListOperations<String, String> forlist = redisTemplate.opsForList();
/* Long aLong = forlist.leftPushAll("k4", "zzz", "zyx", "zy");
System.out.println(aLong);
System.out.println(forlist.range("k4", 0, -1));*/
SetOperations<String, String> forSet = redisTemplate.opsForSet();
//forSet.add("k5", "zzz", "zyx", "zy", "zoe");
//forSet.add("k6","zyx","zy","zed","xxx");
System.out.println(forSet.members("k5"));
System.out.println(forSet.members("k6"));
System.out.println(forSet.intersect("k5", "k6"));
ZSetOperations<String, String> forZset = redisTemplate.opsForZSet();
}
}
1.4.2 RedisTemplate
它是StringRedisTemplate的父类,它类可以存储任意数据类型,但是任意类型必须序列化,默认采用的是jdk的序列化方式。jdk序列化方式阅读能力差,而且占用空间大. 我们在使用是一般需要人为指定序列化方式。
user实体类中需要继承Serializable
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
int id;
String name;
String agress;
}
@Autowired
private RedisTemplate redisTemplate;
//因为user对象在jvm内存中,---放入redis服务器---持久化到磁盘上。---要该对象的类必须序列化
//key和value都是乱码---因为它默认采用的序列化方式jdk的序列化方式。但是阅读不方便。我们一般不是jdk的序列化方式
@Test
public void test01(){
redisTemplate.setKeySerializer(new StringRedisSerializer());//在reids中需序列号,加入后不乱码
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());//在reids中需序列号,加入后不乱码
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("user",new User(1,"zyx","luoyang"));
System.out.println(valueOperations.get("user"));
}
如果每次使用都人为指定序列化方式,统一设置redisTemplate的序列化
package com.example.redis2.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @program: redis2
* @description:
* @author:
* @create: 2023-04-24 16:26
**/
@Configuration
public class RedisConfig {
@Bean //该方法的返回对象交于spring容器管理
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
//field序列化 key field value
template.setHashKeySerializer(redisSerializer);
return template;
}
}
测试
@Test
public void test01(){
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("user",new User(1,"zyx","luoyang"));
System.out.println(valueOperations.get("user"));
}
1.5 springboot连接集群
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
# 设置redis重定向的次数---根据主节点的个数
spring.redis.cluster.max-redirects=3
spring.redis.cluster.nodes=spring.redis.cluster.nodes=192.168.1.100:7001,192.168.1.100:7002,192.168.1.100:7003,192.168.1.100:7004,192.168.1.100:7005,192.168.1.100:7006
2. redis的应用场景
2.1redis可以作为缓存
(1) 缓存的原理
(2)缓存的作用:
减少访问数据库的频率。–提高系统的性能。
(3)什么样的数据适合放入缓存
- 查询频率高的
- 修改频率低的
- 数据安全性要求低的。
(4)如何使用缓存
<?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.3.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ykq</groupId>
<artifactId>qy163-springboot-redis02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>qy163-springboot-redis02</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
</properties>
<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>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</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>
(3)配置文件
server.port=8080
spring.datasource.url=jdbc:mysql:///db1
spring.datasource.password=123456
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#redis?????
spring.redis.host=192.168.1.100
spring.redis.port=6379
#?????
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
(3)servie
@Service
public class StudentServiceImpl implements StudentService{
@Autowired
private StudentMapper studentMapper;
@Autowired
private RedisTemplate redisTemplate;
@Override
public Student findById(Integer id) {
ValueOperations valueOperations = redisTemplate.opsForValue();
Object o = valueOperations.get("student"+id);
if(o!=null){
return (Student) o;
}
Student student = studentMapper.selectById(id);
if (student !=null) {
valueOperations.set("student"+id,student);
}
return student;
}
}
(4)controller
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("findById/{id}")
public Student findById(@PathVariable Integer id){
return studentService.findById(id);
};
}
第一次访问访问之后访问加入redis缓存中不输出sql语句