从零开始:搭建SpringBoot2.X整合Redis框架

最近也不知道写啥,看之前写过Kafka整合Springboot的文章,大家反响还挺热烈的,嘿嘿嘿,就感觉帮助到大家了还挺好的,也算是达到了自己的目的,正好,今天业务模块是springboot整合redis,因为之前做过,所以有现成的代码,cv一下之后就可以了,所以时间比较多,那就给大家整理一下Springboot整合Redis的代码实现吧,从项目搭建到源码实现,下面全都有,耐心看完,相信会对你有所帮助的

好了,话不多说,我们开始吧,同样的,还是建议能够自己在自己的PC端实现一下

一、使用Spring Initializr创建项目web项目

1、File→New→Project

2、点击Next如图所示,命名好Group和Artifact

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

4、创建项目成功后,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 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    4.0.0

   

        org.springframework.boot

        spring-boot-starter-parent

        2.2.2.RELEASE

       


    com.heny

    spring-boot-redis

    0.0.1-SNAPSHOT

    spring-boot-redis

    Demo project for Spring Boot

   

        1.8


   

       

            org.springframework.boot

            spring-boot-starter-web


       

            org.mybatis.spring.boot

            mybatis-spring-boot-starter

            2.1.1


       

            mysql

            mysql-connector-java

            runtime


       

            org.springframework.boot

            spring-boot-starter-test

            test

           

               

                    org.junit.vintage

                    junit-vintage-engine





   

       

           

                org.springframework.boot

                spring-boot-maven-plugin




</project>

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

   

        org.springframework.boot

        spring-boot-starter-data-redis


1234

6、创建JavaBean用于封装数据库数据,需要实现Serializable

package com.henya.springboot.bean;

import java.io.Serializable;

public class Employee implements Serializable{


    private Integer id;

    private String lastName;

    private String email;

    private Integer gender; //性别 1男  0女

    private Integer dId;



    public Employee() {

        super();

    }


    public Employee(Integer id, String lastName, String email, Integer gender, Integer dId) {

        super();

        this.id = id;

        this.lastName = lastName;

        this.email = email;

        this.gender = gender;

        this.dId = dId;

    }


    public Integer getId() {

        return 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() {

        return gender;

    }

    public void setGender(Integer gender) {

        this.gender = gender;

    }

    public Integer getdId() {

        return dId;

    }

    public void setdId(Integer dId) {

        this.dId = dId;

    }

    @Override

    public String toString() {

        return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", dId="

                + dId + "]";

    }

}

注意:在写JavaBean对象时需要实现Serializable接口否则会报以下错误:

Cannot deserialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException

7、整合Mybatis操作数据库,在application.properties配置文件中配置数据源信息

#serverTimezone用于指定时区,不然会报错

spring.datasource.url=jdbc:mysql://localhost:3306/cache?serverTimezone=UTC

spring.datasource.username=root

spring.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.*;

@Mapper

public interface EmployeeMapper {

   @Select("SELECT * FROM employee WHERE id=#{id}")

   public Employee getEmpById(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 emlpoyee WHERE id=#{id}")

   public void delEmpById(Integer id);

   @Insert("INSERT INTO employee(lastName, email, gender, d_id) VALUES (#{lastName}, #{email}, #{gender}, #{dId})")

   public Employee insertEmp(Employee employee);

   @Select("SELECT * FROM employee 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;

import com.henya.springboot.bean.Employee;

import com.henya.springboot.mapper.EmployeeMapper;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.*;

import org.springframework.stereotype.Service;

@CacheConfig(cacheNames = "emp") //抽取缓存的公共配置

@Service

public class EmployeeService {

   @Autowired

   EmployeeMapper employeeMapper;

   /**

    *  @param id

    * @return

    */

   @Cacheable(cacheNames = {"emp"},keyGenerator = "myKeyGenerator")

   public Employee getEmpById(Integer id) {

       System.err.println("开始查询"+ id +"号员工");

       Employee employee = employeeMapper.getEmpById(id);

       return employee;

   }

   /**

    * @CachePut:既调用方法(这个方法必须要执行),又更新缓存数据

    * @param employee

    * @return

    */

   @CachePut(value = "emp",key = "#result.id")

   public Employee updateEmp(Employee employee){

       System.err.println("开始更新" + employee.getId() + "号员工");

       employeeMapper.updateEmp(employee);

       return employee;

   }

   /**

    * @CacheEvict:缓存清除

    * @param id

    */

   @CacheEvict(value = "emp",beforeInvocation = true)

   public void deleteEmp(Integer id){

       System.err.println("删除" + id + "员工");

       int i = 10/0;

   }

10、编写Controller类

package com.henya.springboot.controller;

import com.henya.springboot.bean.Employee;

import com.henya.springboot.service.EmployeeService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RestController;

/**

* @Description:

* @Author:HenYa

* @CreatTime:2019/12/1 12:44

*/

@RestController

public class EmployeeController {

    @Autowired

    EmployeeService employeeService;

    @GetMapping("/emp/{id}")

    public Employee getEmpById(@PathVariable("id") Integer id){

        Employee employee = employeeService.getEmpById(id);

        return employee;

    }

    @GetMapping("/emp")

    public Employee updateEmp(Employee employee){

        Employee emp = employeeService.updateEmp(employee);

        return emp;

    }

}

二、测试SpringBoot整合Redis是否成功

1、在浏览器访问,也可以使用测试类,笔者使用了浏览器访问http://localhost:8080/emp/1进行测试,初次访问时,控制台会提示开始查询1号员工,如图所示。

2、再次访问时,控制台并没有sql日志,如图所示。

3、此时使用RedisDesktopManager工具查看redis时有数据,并且cacheName为emp,如图所示

只是emp对象被序列化了。查看源码可知Redis默认使用Jdk进行序列化。

static RedisSerializer<Object> java(@Nullable ClassLoader classLoader) {

        return new JdkSerializationRedisSerializer(classLoader);

    }

查看RedisSerializer接口的实现有以下几种:

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

三、自定义RedisCacheManager

package com.henya.springboot.config;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.cache.RedisCacheConfiguration;

import org.springframework.data.redis.cache.RedisCacheManager;

import org.springframework.data.redis.cache.RedisCacheWriter;

import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

import org.springframework.data.redis.serializer.RedisSerializationContext;

import org.springframework.data.redis.serializer.RedisSerializer;

/**

* @Description:

* @Author:HenYa

* @CreatTime:2019/12/6 20:50

*/

@Configuration

public class MyRedisConfig {

    @Bean

    public RedisCacheManager empCacheManager(RedisConnectionFactory redisConnectionFactory){

        //RedisCacheManager redisCacheManager = new RedisCacheManager(redisConnectionFactory);

        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);

        RedisSerializer<Object> redisSerializer = new GenericJackson2JsonRedisSerializer();

        RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer);

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);

        // 默认会将CacheName作为key的前缀

        return  new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);

    }

    }

此时,Redis中缓存数据就以Json的格式进行序列化,如图所示。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容