Redis
什么是Redis
redis属于NoSql分类,它把数据都是缓存在内存中的,它是一种键值数据库(缓存数据库),我们都知道内存的读写效率跟硬盘不是一个级别的,最后redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件。既然用redis读取效率那么高,最后内容也会添加到磁盘那么我们就当然要使用它了。
Redis的作用
是一种最基本、最常用的数据库优化方案,能降低数据库的查询压力
使用场景
数据更改不频繁,经常被访问
下载安装
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.8.4.RELEASE</version>
</dependency>
redis.host=127.0.0.1
redis.port=6379
redis.password=123456
redis.maxIdle=300
redis.maxWaitMillis=1000
redis.maxTotal=600
redis.testOnBorrow=true
redis.testOnReturn=true
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--设置连接池-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}"/>
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
<property name="testOnReturn" value="${redis.testOnReturn}" />
</bean>
<!--设置链接属性-->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName"><value>${redis.host}</value></property>
<property name="port"><value>${redis.port}</value></property>
<property name="password"><value>${redis.password}</value></property>
<property name="poolConfig"><ref bean="poolConfig"></ref></property>
<property name="timeout"><value>100000</value></property>
</bean>
<!-- Jedis模板配置 -->
<bean id="redisMapper" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
</beans>
Service层集成
package org.neuedu.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.neuedu.mapper.ProductsMapper;
import org.neuedu.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service
public class ProductsService {
@Autowired
ProductsMapper productsMapper;
@Autowired
RedisTemplate redisTemplate;
public List<Product> getAll() {
// 判断redis中是否有商品数据,如果有直接返回,如果没有,连接mysql,得到结果返回
// 并在redis中保存一份
try {
Object products = redisTemplate.opsForValue().get("products");
if (products == null) {
List<Product> productsList = productsMapper.getAll();
redisTemplate.opsForValue().set("products", new ObjectMapper().writeValueAsString(productsList));
// 设置过期时长
redisTemplate.expire("products",60, TimeUnit.SECONDS);
return productsList;
} else {
List<Product> list = new ObjectMapper().readValue((String)products, List.class);
return list;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public int update(String id, String name) {
// 如果 DML 操作,修改数据库,要同步更新redis
int i = productsMapper.update(id, name);
redisTemplate.delete("products");
return i;
}
}
SSM中使用
###踩坑
1.检查依赖(3个)和配置文件
2.如果运行期间 ClassNotFoundException
3.项目结构 - > Modules - >dependencies ->重新添加3个依赖
4.项目结构 - > Modules - >Artifacts -> 重新设置打包配置
5.删除out,clean,项目重启
SpringBoot集成Redis
1.创建项目
####2.对redis进行配置
server.port=8888
spring.redis.host=127.0.0.1
spring.redis.password=123
spring.redis.port=6379
spring.redis.database=0
3.需要缓存的实体类必须实现Serializable
package org.neuedu.redis01.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable { // 标识接口
private Integer id;
private String name;
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "Asia/Shanghai")
private Date birhtday;
// get,set,toString
}
4.在启动类上需要添加启动缓存注解
package org.neuedu.redis01;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching // 开启缓存
public class Redis01Application {
public static void main(String[] args) {
SpringApplication.run(Redis01Application.class, args);
}
}
5.写Service测试
https://www.cnblogs.com/fashflying/p/6908028.html
@Cacheable : 将方法的返回值缓存
@Cacheable 可以指定三个属性,value、key和condition。
- value : 缓存的名字
- key : 缓存的key值,#是取参数,下例可以写成 #id ,也可以写成 #p0,p指参数,0是索引
- condition: 缓存条件
@Service public class UserService { @Autowired UserMapper userMapper; @Cacheable(value = {"user"},key = "#id") public User serchUserById(Integer id) { return userMapper.serchUserById(id); } }
@CacheEvict : 将返回值缓存清空
@CacheEvict 可以指定5个属性value、key、condition、allEntries和beforeInvocation
allEntries : 指定是否全部删除
beforeInvocation : 指定删除时间的,是爱方法调用前还是调用后package org.neuedu.redis01.service; import org.neuedu.redis01.mapper.UserMapper; import org.neuedu.redis01.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; import org.springframework.stereotype.Service; import java.util.List; @Service //@CacheConfig(cacheNames = "userid") public class UserService { @Autowired UserMapper userMapper; @Cacheable(value = {"user"},key = "#id") public User serchUserById(Integer id) { return userMapper.serchUserById(id); } @Cacheable(value = {"users"},key = "#root.methodName") public List<User> serchUsers() { return userMapper.serchUsers(); } // @CacheEvict(value = {"user"},key = "#id") @Caching(evict = { @CacheEvict(value="user",key = "#id"), @CacheEvict(value="users",allEntries=true) }) public int delUserById(Integer id) { return userMapper.delUserById(id); } }
lue = {“user”},key = “#id”)
@Caching(evict = { @CacheEvict(value="user",key = "#id"), @CacheEvict(value="users",allEntries=true) }) public int delUserById(Integer id) { return userMapper.delUserById(id); }
}