欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解Spring Boot使用redis实现数据缓存

程序员文章站 2024-02-29 11:30:16
基于spring boot 1.5.2.release版本,一方面验证与redis的集成方法,另外了解使用方法。 集成方法 1、配置依赖 修改pom.xml,增加如下...

基于spring boot 1.5.2.release版本,一方面验证与redis的集成方法,另外了解使用方法。

集成方法

1、配置依赖

修改pom.xml,增加如下内容。

  <dependency> 
    <groupid>org.springframework.boot</groupid> 
    <artifactid>spring-boot-starter-data-redis</artifactid> 
  </dependency> 

2、配置redis

修改application.yml,增加如下内容。

spring:
  redis:
    host: localhost 
    port: 6379
    pool:
      max-idle: 8 
      min-idle: 0
      max-active: 8
      max-wait: -1

3、配置redis缓存

package net.jackieathome.cache;

import java.lang.reflect.method;

import org.springframework.cache.cachemanager;
import org.springframework.cache.annotation.cachingconfigurersupport;
import org.springframework.cache.annotation.enablecaching;
import org.springframework.cache.interceptor.keygenerator;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.cache.rediscachemanager;
import org.springframework.data.redis.connection.redisconnectionfactory;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.data.redis.serializer.jackson2jsonredisserializer;

import com.fasterxml.jackson.annotation.jsonautodetect;
import com.fasterxml.jackson.annotation.propertyaccessor;
import com.fasterxml.jackson.databind.objectmapper;

@configuration
@enablecaching // 启用缓存特性
public class redisconfig extends cachingconfigurersupport {
  // 缓存数据时key的生成器,可以依据业务和技术场景自行定制
// @bean
// public keygenerator customizedkeygenerator() {
//   return new keygenerator() {
//     @override
//     public object generate(object target, method method, object... params) {
//       stringbuilder sb = new stringbuilder();
//       sb.append(target.getclass().getname());
//       sb.append(method.getname());
//       for (object obj : params) {
//         sb.append(obj.tostring());
//       }
//       return sb.tostring();
//     }
//   };
//
// }
  // 定制缓存管理器的属性,默认提供的cachemanager对象可能不能满足需要
  // 因此建议依赖业务和技术上的需求,自行做一些扩展和定制
  @bean
  public cachemanager cachemanager(@suppresswarnings("rawtypes") redistemplate redistemplate) {
    rediscachemanager rediscachemanager = new rediscachemanager(redistemplate);
    rediscachemanager.setdefaultexpiration(300);
    return rediscachemanager;
  }

  @bean
  public redistemplate<string, string> redistemplate(redisconnectionfactory factory) {
    stringredistemplate template = new stringredistemplate(factory);
    jackson2jsonredisserializer jackson2jsonredisserializer = new jackson2jsonredisserializer(object.class);
    objectmapper om = new objectmapper();
    om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any);
    om.enabledefaulttyping(objectmapper.defaulttyping.non_final);
    jackson2jsonredisserializer.setobjectmapper(om);
    template.setvalueserializer(jackson2jsonredisserializer);
    template.afterpropertiesset();
    return template;
  }
}

验证集成后的效果

考虑到未来参与的项目基于mybatis实现数据库访问,而利用缓存,可有效改善web页面的交互体验,因此设计了如下两个验证方案。

方案一

在访问数据库的数据对象上增加缓存注解,定义缓存策略。从测试效果看,缓存有效。

1、页面控制器

package net.jackieathome.controller;

import java.util.list;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.restcontroller;

import net.jackieathome.bean.user;
import net.jackieathome.dao.userdao;
import net.jackieathome.db.mapper.usermapper;

@restcontroller
public class usercontroller {

  @autowired
  private userdao userdao;

  @requestmapping(method = requestmethod.get, value = "/user/id/{id}")
  public user finduserbyid(@pathvariable("id") string id) {
    return userdao.finduserbyid(id);
  }

  @requestmapping(method = requestmethod.get, value = "/user/create")
  public user createuser() {
    long time = system.currenttimemillis() / 1000;

    string id = "id" + time;
    user user = new user();
    user.setid(id);
    userdao.createuser(user);

    return userdao.finduserbyid(id);
  }
}

2、mapper定义

package net.jackieathome.db.mapper;

import java.util.list;

import org.apache.ibatis.annotations.mapper;
import org.apache.ibatis.annotations.param;
import org.springframework.cache.annotation.cacheconfig;
import org.springframework.cache.annotation.cacheput;
import org.springframework.cache.annotation.cacheable;

import net.jackieathome.bean.user;


@mapper
public interface usermapper {

  void createuser(user user);

  user finduserbyid(@param("id") string id);
}

3、数据访问对象

package net.jackieathome.dao;

import java.util.arraylist;
import java.util.list;

import org.apache.ibatis.annotations.param;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.cache.annotation.cacheconfig;
import org.springframework.cache.annotation.cacheput;
import org.springframework.cache.annotation.cacheable;
import org.springframework.stereotype.component;
import org.springframework.transaction.annotation.transactional;

import net.jackieathome.bean.user;
import net.jackieathome.db.mapper.usermapper;

@component
@cacheconfig(cachenames = "users")
@transactional
public class userdao {
  private static final logger log = loggerfactory.getlogger(userdao.class);
  @autowired
  private usermapper usermapper;

  @cacheput(key = "#p0.id")
  public void createuser(user user) {
    usermapper.createuser(user);
    log.debug("create user=" + user);
  }

  @cacheable(key = "#p0")
  public user finduserbyid(@param("id") string id) {
    log.debug("find user=" + id);
    return usermapper.finduserbyid(id);
  }
}

方案二

直接在mapper定义上增加缓存注解,控制缓存策略。从测试效果看,缓存有效,相比于方案一,测试代码更加简洁一些。

1、页面控制器

package net.jackieathome.controller;

import java.util.list;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.restcontroller;

import net.jackieathome.bean.user;
import net.jackieathome.dao.userdao;
import net.jackieathome.db.mapper.usermapper;

@restcontroller
public class usercontroller {

  @autowired
  private usermapper usermapper;

  @requestmapping(method = requestmethod.get, value = "/user/id/{id}")
  public user finduserbyid(@pathvariable("id") string id) {
    return usermapper.finduserbyid(id);
  }

  @requestmapping(method = requestmethod.get, value = "/user/create")
  public user createuser() {
    long time = system.currenttimemillis() / 1000;

    string id = "id" + time;
    user user = new user();
    user.setid(id);
    usermapper.createuser(user);

    return usermapper.finduserbyid(id);
  }
}

2、mapper定义

package net.jackieathome.db.mapper;

import java.util.list;

import org.apache.ibatis.annotations.mapper;
import org.apache.ibatis.annotations.param;
import org.springframework.cache.annotation.cacheconfig;
import org.springframework.cache.annotation.cacheput;
import org.springframework.cache.annotation.cacheable;

import net.jackieathome.bean.user;

@cacheconfig(cachenames = "users")
@mapper
public interface usermapper {

  @cacheput(key = "#p0.id")
  void createuser(user user);

  @cacheable(key = "#p0")
  user finduserbyid(@param("id") string id);
}

总结

上述两个测试方案并没有优劣之分,仅是为了验证缓存的使用方法,体现了不同的控制粒度,在实际的项目开发过程中,需要依据实际情况做不同的决断。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。