这篇文章主要介绍“SpringBoot如何使用Redis缓存”,在日常操作中,相信很多人在SpringBoot如何使用Redis缓存问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”SpringBoot如何使用Redis缓存”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
1 redis是安装在linux上
安装docker
yum install docker
2)开启docker
service docker start
2 安装Redis
可到这个网站查怎么安装 https://hub.docker.com
开启redis
3 创建springBoot项目(细节不在赘述)
pom.xml文件
<?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.1.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.mao</groupId> <artifactId>spring-cache</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-cache</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> <scope>runtime</scope> </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> </plugin> </plugins> </build>
</project>
4 提供一个entity类 //这个文件来自尚学堂里的
public class Employee implements Serializable
private Integer id; private String lastName; private String email; private Integer gender; //性别 1男 0女 private Integer dId;
。。。。。。(简写啦)
}
5 redis的客户请自己安装
相关知识点请到这个网站学习 http://www.redis.cn 里面有很多案例
6 配置属性 application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/spring_cache
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#启动驼峰命名法
mybatis.configuration.map-underscore-to-camel-case=true
logging.level.mao.springcache.mapper=debug
#由于我安装的redis没密码,只给主机地址就可以啦
spring.redis.host=192.168.1.139
7 测试下Redis的缓存首先看下源码是怎么写的
public class SpringCacheApplicationTests {
//操作键值对,jdk默认的序列化机制 @Autowired RedisTemplate redisTemplate; //操作字符串 @Autowired StringRedisTemplate stringRedisTemplate; @Autowired RedisTemplate<Object,Employee> redisTemplate1; [@Test](https://my.oschina.net/azibug) public void test1(){ //stringRedisTemplate.opsForValue().append("hello","hello"); System.out.println(stringRedisTemplate.opsForValue().get("hello")); } [@Test](https://my.oschina.net/azibug) public void test2(){ Employee employee = employeeMapper.getEmployee(1); redisTemplate.opsForValue().set("emp-01",employee); } @Test public void contextLoads() { Employee employee = employeeMapper.getEmployee(1); System.out.println(employee.toString()); }
}
上面test1测试结果:
上面test2测试结果:
接下来解决上面难看的问题:我们重写RedisTemplate 我们想让缓存查看的时候为json
@Configuration
public class myredis {
@Bean public RedisTemplate<Object, Employee> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object,Employee> template = new RedisTemplate<Object, Employee>(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class); template.setDefaultSerializer(ser); return template; } }
之前一张图已经展示过原理
下面这张图解释这句haul template.setDefaultSerializer(ser);
重新测试的结果
8 接下啦讲spring项目中使用 //EmployeeService类
@Service
public class EmployeeService {
@Autowired EmployeeMapper employeeMapper; //将方法的结果缓存,以后请求相同的数据,直接从缓存中获取,不用调用方法 //CacheManner管理多个Cache组件,对缓存的真正CRUD组件,每个缓存组有自己唯一一个名字 //几个属性,指定缓存的名字key,可以指定@param id @Cacheable(cacheNames ={"emp"}) public Employee getEmp(Integer id){ System.out.println("查询"+id+"员工"); Employee employee = employeeMapper.getEmployee(id); return employee; } //达到了同步更新缓存的目的,取缓存的key要与放缓存的key相同 @CachePut(cacheNames = "emp",key = "#employee.id") public Employee updateEmp(Employee employee){ employeeMapper.updateEmp(employee); return employee; } @CacheEvict(value = "emp",key = "#id") public void deleteEmp(Integer id){ System.out.println("deleteEMp"+id); public Employee getEmployeeByLastName(String lastName){ return employeeMapper.getEmpByLastName(lastName); }
}
EmployeeMapper代码
public interface EmployeeMapper {
@Select("select * from employee where id =#{id}") public Employee getEmployee(Integer id); @Update("update employee set lastName=#{lastName},email=#{email},gender=#{gender},d_id=#{dId} where id =#{id}") public void updateEmp(Employee employee); @Delete("delete * from employee where id=#{id}") public void deleteEmpById(Integer id); @Insert("insert into employee(lastName,email,gender,d_id) values(#{lastName},#{email},#{gender},#{dId})") public void insertEmpployee(Employee employee); @Select("select * from employee where lastName=#{lastName}") public Employee getEmpByLastName(String name);
}
EmployeeController.java
@RestController
public class EmployeeController {
@Autowired EmployeeService employeeService; @RequestMapping("/emp/{id}") public Employee getEmployee(@PathVariable("id") Integer id){ Employee employee=employeeService.getEmp(id); return employee; } @GetMapping("/emp") public Employee updateEmp(Employee employee){ System.out.println("员工更新的方法调用"); Employee employee1 = employeeService.updateEmp(employee); return employee1; } @GetMapping("/delete") public String deleteEmp(Integer id){ System.out.println("删除一个员工的相关信息"); return "删除员工"; } @RequestMapping("/emps/{lastName}") public Employee getByLastName(@PathVariable("lastName") String lastName){ return employeeService.getEmployeeByLastName(lastName); }
}
应用类的配置 注意
下面是我最想写的,当时看尚学堂的视频一直写不出来的,由于使用的版本不同,我使用的使用2.xxx
下面是我配置的RedisCacheManager
@Configuration
public class myredis {
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory){
Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class); RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(ser)); RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(config).build(); return cacheManager;
}
} 这个写法和1.xx明显不同
下面是2.xx源码
下面这副图解释这句
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(ser));
测试结果
到此,关于“SpringBoot如何使用Redis缓存”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。