如何使用Redis框架构建SpringBoot2.X

分类:编程技术 时间:2024-02-20 15:19 浏览:0 评论:0
0
本文主要介绍Redis框架如何构建SpringBoot2.X。文章中的介绍非常详细,有一定的参考价值。感兴趣的朋友一定要读一下!

1.使用Spring Initializr创建项目Web项目

1.文件→新建→项目

2.点击Next如图所示如图所示,为Group和Artifact命名

3. Next之后,如图所示,勾选需要的依赖,Spring Initializr会自动导入需要的starter

4.项目创建成功后,pom.xml文件中的依赖如下

 <项目 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">4.0.0 org .springframework.bootspring-boot-starter-parent2.2.2.RELEASE < groupId>com.henyspring-boot-redis0.0.1-SNAPSHOTspring-boot-redis演示项目对于 Spring Boot1.8org.springframework.bootspring-boot -starter-weborg .mybatis.spring.bootmybatis-spring-boot-starter2.1.1< /version>mysqlmysql-connector-java运行时org. springframework.bootspring-boot-starter-test测试org.junit.vintage朱尼特复古-engineorg.springframework.boot spring-boot- maven-plugin

5.在pom.xml文件中添加redis starter

org.springframework.bootspring-boot-starter-data- redis

6.创建一个JavaBean来封装数据库数据,需要实现Serialized

package com.henya.springboot.bean;import java. io.Serialized;公共类 Employee 实现 Serialized{private Integer id;private String lastName;private String email;private Integer sex; //性别1男0女 private Integer dId;public Employee() {super();}public Employee( Integer id, String lastName, String email, Integer sex, Integer dId) {super();this.id = id; this.lastName = 姓氏;this.email = 电子邮件;this.gender = 性别;this.dId = dId;}public Integer getId() {返回id; }public void setId(Integer id) {this.id = id;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public String getEmail() {return email; }public void setEmail(String email) {this.email = email;}public Integer getGender() {返回性别;}public void setGender(Integer sex) {this.gender = 性别;}public Integer getdId() {return dId; }public void setdId(Integer dId) {this.dId = dId;}@Overridepublic String toString() {return "员工 [id=" + id + ", lastName=" + lastName + ", email=" + email + " ,gender="+gender+",dId="+dId+"]";}}

注意:
在编写JavaBean对象时,需要实现Serialized接口,否则出现以下情况会报错:

无法反序列化;嵌套异常是org.springframework.core.serializer.support.SerializationFailedException

7。集成Mybatis操作数据库和d 在application.properties配置文件中配置数据源信息

#serverTimezone用于指定时区,否则会报错 spring.datasource.url=jdbc :mysql://localhost:3306/cache?serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=123456#开启驼峰式命名规则 mybatis.configuration.map- underscore-to-camel-case=true#日志级别logging.level.com.henya.springboot.mapper=debug

8.使用带注解版本的Mybatis创建Mapper

package com.henya.springboot.mapper;import com.henya.springboot.bean.Employee;import org.apache.ibatis .annotations.*;@Mapperpublic 接口 EmployeeMapper { @Select("SELECT * FROM 员工 WHERE id=#{id}") public Employee getEmpById(Integer id); @Update("更新员工设置姓氏=#{姓氏},电子邮件=#{电子邮件},性别=#{性别},d_id=#{dId} WHERE id=#{id}") public void updateEmp(员工员工) ; @Delete("删除 FROM emlpoyee WHERE id=#{id}") public void delEmpById(Integer id); @Insert("INSERT INTO 员工(姓氏、电子邮件、性别、d_id) VALUES (#{lastName}, #{email}, #{gender }, #{dId})") public Employee insertEmp(EmployeeEmployee); @Select("从员工中选择 * WHERE lastName =#{lastName}") public Employee getEmpByLastName(String lastName);}

注意:
需要使用@MapperScan注解来扫描Mapper所在的接口,只需要将其添加到主程序类中即可。可以。另外,使用@EnableCaching来启用缓存。

@MapperScan("com.henya.springboot.mapper")@SpringBootApplication@EnableCaching //启用缓存 public class SpringBootRedisApplication {public static void main(String[] args) {SpringApplication .run(SpringBootRedisApplication.class, args);}}

9. 编写一个Service类,用于访问数据库或redis缓存

package com.henya .springboot.service;导入com.henya.springboot.bean.Employee;导入 com.henya.springboot.mapper.EmployeeMapper;导入 org. springframework.beans.factory.annotation.Autowired;import org.springframework.cache.annotation.*;import org.springframework.stereotype.Service;@CacheConfig(cacheNames = "emp") //提取缓存的公共配置 @Servicepublic class EmployeeService { @Autowired EmployeeMapper 员工映射器; /** * @param id * @return */ @Cacheable(cacheNames = {"emp"},keyGenerator = "myKeyGenerator") public Employee getEmpById(Integer id) { System.err.println("开始查询" + id + “员工编号”);员工员工=employeeMapper.getEmpById(id);返回员工; } /** * @CachePut:均调用方法(该方法必须执行),并更新缓存数据 * @paramEmployee * @return */ @CachePut(value = "emp",key = "#result.id" ) public Employee updateEmp(EmployeeEmployee){ System.err .println("开始更新" + employee.getId() + "员工编号");员工Mapper.updateEmp(员工);返回员工; } /** * @CacheEvict: Ca清除* @param id */ @CacheEvict(value = "emp",beforeInspiration = true) public void deleteEmp(Integer id){ System.err.println("Delete" + id + "Employee"); }整数 i = 10/0; }

10、编写Controller类

package com.henya.springboot.controller;import com.henya.springboot.bean.Employee;import com .henya.springboot.service.EmployeeService;导入org.springframework.beans.factory.annotation.Autowired;导入org.springframework.web.bind.annotation.GetMapping;导入org.springframework.web.bind.annotation.PathVariable;导入org .springframework.web.bind.annotation.RestController;/** * @Description: * @Author: HenYa * @CreatTime: 2023/12/1 12:44 */ @RestControllerpublic class EmployeeController { @Autowired EmployeeServiceEmployeeService; @GetMapping("/emp/{id}") public Employee getEmpById(@PathVariable("id") Integer id){ Employee 员工 = employeeService.getEmpById(id);返回员工; } @GetMapping("/emp") public Employee updateEmp(Employee 员工){ 员工 emp = employeeService.updateEmp(employee);返回雇员; }}

2.测试SpringBoot集成Redis是否成功

1.在浏览器中访问时也可以使用测试类。我使用浏览器访问http://localhost:8080/emp/1进行测试。第一次访问时,控制台会提示开始查询1号员工,如图。

2.再次访问时,控制台没有SQL日志,如图。

3.此时使用Re,disDesktopManager工具检查redis时有数据,cacheName为emp,如图

只序列化emp对象。查看源码可以看到,Redis默认使用Jdk进行序列化。

静态RedisSerializer java(@Nullable ClassLoader classLoader) { return new JdkSerializationRedisSerializer(classLoader); }

查看RedisSerializer接口的实现as如下几种:

我们常用的是json格式的序列化。但需要自定义RedisCacheManager。

3.自定义RedisCacheManager

package com.henya.springboot.config;import org.springframework.context.annotation.Bean;import org. springframework.context.annotation.Configuration;导入 org.springframework.data.redis.cache.RedisCacheConfiguration;导入 org.springframework.data.redis.cache.RedisCacheManager;导入 org.springframework.data.redis.cache.RedisCacheWriter;导入 org. springframework.data.redis.connection.RedisConnectionFactory;导入org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;导入org.springframework.data.redis.serializer.RedisSerializationContext;导入org.springframework.data.redis.serializer.RedisSerializer;/* * * @Description: * @作者:HenYa * @CreatTime:2023/12/6 20:50 */@Configurationpublic class MyRedisConfig { @Bean public RedisCacheManager empCacheManager(RedisConnectionFactory redisConnectionFactory){ //RedisCacheManager redisCacheManager = new RedisCacheManager(redisConnectionFactory); RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); RedisSerializer redisSerializer = new GenericJackson2JsonRedisSerializer(); RedisSerializationContext.SerializationPairpair = RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer ; 以上就是《如何使用Redis框架搭建SpringBoot2.X》一文的全部内容,感谢您的阅读!希望分享的内容对您有所帮助向大家寻求帮助,以及更多相关知识,欢迎关注行业资讯频道!

1. 本站所有资源来源于用户上传或网络,仅作为参考研究使用,如有侵权请邮件联系站长!
2. 本站积分货币获取途径以及用途的解读,想在本站混的好,请务必认真阅读!
3. 本站强烈打击盗版/破解等有损他人权益和违法作为,请各位会员支持正版!
4. 编程技术 > 如何使用Redis框架构建SpringBoot2.X

用户评论