spring 整合使用框架学习使用spring framework

SpringBoot配置并使用Redis缓存服务

2020-11-04  本文已影响0人  singleZhang2010

概述

Redis是一款高性能key-value数据库,有丰富的数据类型string、list、hash、set、zset。

常用的应用场景

缓存、消息队列、session共享、分布式ID、分布式锁、关注/点赞、排行榜等等,我们这篇主要来讲缓存的应用

开始在SpringBoot项目中实践

  1. 现在pom.xml中加入redis依赖
        <!-- redis 缓存操作 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
  1. 在yml配置文件中加入redis配置信息
spring:
  redis:
    database: 0  # Redis数据库索引(默认为0)
    host: localhost # Redis服务器地址
    port: 6379  # Redis服务器连接端口
    password:   # Redis服务器连接密码(默认为空)
    lettuce:
      pool:
        max-active: 8  # 连接池最大连接数(使用负值表示没有限制) 默认 8
        max-wait: -1   # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
        max-idle: 8    # 连接池中的最大空闲连接 默认 8
        min-idle: 0    # 连接池中的最小空闲连接 默认 0
  cache:
    type: redis

在SpringBoot2.X,redis默认使用lettuce,基于Netty性能高于以前的jedis。

  1. 创建RedisConfig.java配置类
package com.zhlab.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @ClassName RedisConfig
 * @Description //Redis缓存配置类
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2020/11/3 0003 下午 2:15
 **/
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();

        // 配置连接工厂
        template.setConnectionFactory(factory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(mapper);

        // 值采用json序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}

  1. DAO层不变,按之前的SysAdminUserRepository.java
public interface SysAdminUserRepository extends JpaRepository<SysAdminUser,Long>, Serializable {
    // 就这么简单?
    // 对,就这么简单,什么都不用写,这是Spring Data JPA 默认帮我们实现了基本的数据库操作
    // 如果需要扩展,可以自定义符合Spring Data JPA规则的查询方法,由框架将其自动解析为SQL
}
  1. Service层中加入缓存注解@CacheConfig、@Cacheable、@CachePut、@CacheEvict,SysAdminUserService.java,
package com.zhlab.demo.service;

import com.zhlab.demo.dao.SysAdminUserRepository;
import com.zhlab.demo.model.SysAdminUser;
import com.zhlab.demo.utils.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName SysAdminUserService
 * @Description //SysAdminUserService
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2020/10/31 0031 上午 9:45
 **/
@CacheConfig(cacheNames = "users")
@Service
public class SysAdminUserService {

    @Autowired
    SysAdminUserRepository sysAdminUserRepository;

    @Cacheable(key="'user_'+#userId")
    public SysAdminUser findUser(Long userId){
        return sysAdminUserRepository.findById(userId).orElse(null);
    }

    @CachePut(key="'user_'+#result.adminUserId")
    public SysAdminUser save(SysAdminUser user){
        return sysAdminUserRepository.save(user);
    }

    @CacheEvict(key="'user_'+#userId")
    public void deleteUser(Long userId) {
        sysAdminUserRepository.findById(userId).ifPresent(sysAdminUserRepository::delete);
    }
}

  1. 接口层,UserController.java 加入增、删、查来测试一下
package com.zhlab.demo.controller;

import com.zhlab.demo.model.SysAdminUser;
import com.zhlab.demo.service.SysAdminUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName UserController
 * @Description //用户接口层
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2020/10/31 0031 上午 9:43
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    SysAdminUserService sysAdminUserService;

    

    @ApiOperation(value = "方法名:用户信息", notes = "获取用户信息")
    @GetMapping("/{userId}")
    public SysAdminUser findUser(@PathVariable Long userId){
        return sysAdminUserService.findUser(userId);
    }

    @ApiOperation(value = "方法名:新增用户", notes = "新增用户")
    @PostMapping("/add")
    public SysAdminUser addUser(@RequestBody SysAdminUser user){
        return sysAdminUserService.save(user);
    }

    @ApiOperation(value = "方法名:删除用户信息", notes = "删除用户信息")
    @GetMapping("/delete/{userId}")
    public void deleteUser(@PathVariable Long userId){
        sysAdminUserService.deleteUser(userId);
    }

}

  1. 启动项目,打开http://localhost:8080/swagger-ui.html来调试接口
接口

redisManager中,可以看到现在redis里现在还没数据


redisManager
  1. 调试一下查询userId=1的用户信息


    返回结果

    此时查看一下redis中的数据,已经新增了一条缓存数据


    redis
    之后查询这用户,数据会从缓存中获取。
    新增、删除调试方法类同。

9.接下来再增加另一种,通过redisTemplate来操作缓存数据,修改之前的UserController.java,

package com.zhlab.demo.controller;

import com.zhlab.demo.model.SysAdminUser;
import com.zhlab.demo.service.SysAdminUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName UserController
 * @Description //用户接口层
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2020/10/31 0031 上午 9:43
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    private static final int expireTime = 30;

    @Autowired
    SysAdminUserService sysAdminUserService;

    @Autowired
    RedisTemplate redisTemplate;


    @ApiOperation(value = "方法名:用户信息", notes = "获取用户信息")
    @GetMapping("/{userId}")
    public SysAdminUser findUser(@PathVariable Long userId){

        //从缓存获取有无这个用户信息
        SysAdminUser userInfo = getCacheObject("users::user_"+userId);
        if(userInfo == null){
            //没有,则从数据库查询
            userInfo =sysAdminUserService.findUser(userId);

            //设置缓存
            setCacheObject("users::user_"+userId,userInfo,expireTime,TimeUnit.MINUTES);
        }
        return sysAdminUserService.findUser(userId);
    }

    @ApiOperation(value = "方法名:新增用户", notes = "新增用户")
    @PostMapping("/add")
    public SysAdminUser addUser(@RequestBody SysAdminUser user){
        return sysAdminUserService.save(user);
    }

    @ApiOperation(value = "方法名:删除用户信息", notes = "删除用户信息")
    @GetMapping("/delete/{userId}")
    public void deleteUser(@PathVariable Long userId){

        sysAdminUserService.deleteUser(userId);
    }


    /**
     * 获取缓存
     * */
    private <T> T getCacheObject(String key){
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 设置缓存
     * */
    private <T> ValueOperations<String, T> setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        operation.set(key, value, timeout, timeUnit);
        return operation;
    }
}

  1. 继续来调试/user/{userId}这个接口


    接口调试

查看结果


redis

总结

SpringBoot中使用redis缓存的方法就介绍到这儿,需要熟练掌握,因为大型项目中缓存的应用非常广泛。

项目地址

https://gitee.com/kaixinshow/springboot-note

返回【Spring Boot学习】目录

上一篇下一篇

猜你喜欢

热点阅读