千家信息网

SpringBoot如何使用Redis缓存

发表于:2024-11-17 作者:千家信息网编辑
千家信息网最后更新 2024年11月17日,这篇文章主要介绍"SpringBoot如何使用Redis缓存",在日常操作中,相信很多人在SpringBoot如何使用Redis缓存问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对
千家信息网最后更新 2024年11月17日SpringBoot如何使用Redis缓存

这篇文章主要介绍"SpringBoot如何使用Redis缓存",在日常操作中,相信很多人在SpringBoot如何使用Redis缓存问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"SpringBoot如何使用Redis缓存"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

1 redis是安装在linux上

  1. 安装docker

yum install docker

2)开启docker

service docker start

2 安装Redis

可到这个网站查怎么安装 https://hub.docker.com

开启redis

3 创建springBoot项目(细节不在赘述)

pom.xml文件

     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">         4.0.0    org.springframework.boot            spring-boot-starter-parent            2.1.6.RELEASE                     com.maospring-cache0.0.1-SNAPSHOTspring-cacheDemo project for Spring Boot    1.8                            org.springframework.boot                        spring-boot-starter-jdbc                                        org.springframework.boot                        spring-boot-starter-data-redis                                                org.springframework.boot                        spring-boot-starter-web                                                org.mybatis.spring.boot                        mybatis-spring-boot-starter                        2.0.1                                        mysql                        mysql-connector-java                        5.1.47                        runtime                                                org.springframework.boot                        spring-boot-starter-test                        test                                                                            org.springframework.boot                                    spring-boot-maven-plugin                                                            

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默认的序列化机制@AutowiredRedisTemplate redisTemplate;//操作字符串@AutowiredStringRedisTemplate stringRedisTemplate;@AutowiredRedisTemplate 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);}@Testpublic void contextLoads() {    Employee employee = employeeMapper.getEmployee(1);    System.out.println(employee.toString());}

}

上面test1测试结果:

上面test2测试结果:

接下来解决上面难看的问题:我们重写RedisTemplate 我们想让缓存查看的时候为json

@Configuration

public class myredis {

@Beanpublic RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {    RedisTemplate template = new RedisTemplate();            template.setConnectionFactory(redisConnectionFactory);            Jackson2JsonRedisSerializer ser = new Jackson2JsonRedisSerializer(Employee.class);            template.setDefaultSerializer(ser);            return template;}}

之前一张图已经展示过原理

下面这张图解释这句haul template.setDefaultSerializer(ser);

重新测试的结果

8 接下啦讲spring项目中使用 //EmployeeService类

@Service

public class EmployeeService {

@AutowiredEmployeeMapper 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 {

@AutowiredEmployeeService 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 ser = new Jackson2JsonRedisSerializer(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缓存"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

0