SpringBoot+Mybatis+Redis 实现缓存

9 篇文章 0 订阅
7 篇文章 0 订阅
搭建环境:
IDEA,jdk1.8,springboot1.5.3

新建springboot项目  依赖选择如下


springboot的推荐项目结构如下

其中
  • root package结构:com.example.myproject
  • 应用主类Application.java置于root package下,通常我们会在应用主类中做一些框架配置扫描等配置, 我们放在root package下可以帮助程序减少手工配置来加载到我们希望被Spring加载的内容
  • 实体(Entity)与数据访问层(Repository)置于com.example.myproject.domain包下
  • 逻辑层(Service)置于com.example.myproject.service包下
  • Web层(web)置于com.example.myproject.web包下
搭建完的项目结构如下

本文采用mybatis-generator自动生成mapper,dao,entity,具体操作步骤见
https://blog.csdn.net/sinat_29774479/article/details/78542626  Intellji IDE使用mybatis-generator自动生成mybatis相关文件

删除application.properties  新建application.yml,
server:
    port: 8080

spring:
    datasource:
        name: test
        url: jdbc:mysql://127.0.0.1:3306/world
        username: root
        password: 1234
        # 使用 druid 数据源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20

redis:
    host: 171.188.96.88
    port: 6379
    password: root
mybatis:
    mapper-locations: classpath:mapper/*.xml
    type-aliases-package: com.redis.domain

#pagehelper 分页插件
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql

添加redis的配置类,继承CachingConfigurerSupport根据自己需要重写方法
package com.redis.config;

import com.fasterxml.jackson.annotation. JsonAutoDetect ;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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 java.lang.reflect.Method;


/**
* Redis 缓存配置类
*
* @author wl
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/* 定义缓存数据 key 生成策略的 bean
包名 + 类名 + 方法名 + 所有参数
*/
@Bean
public KeyGenerator wiselyKeyGenerator() {
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();
}
};

}

/* 要启用 spring 缓存支持 , 需创建一个 CacheManager bean CacheManager 接口有很多实现,这里 Redis 的集成,用 RedisCacheManager 这个实现类
Redis 不是应用的共享内存,它只是一个内存服务器,就像 MySql 似的,
我们需要将应用连接到它并使用某种 语言 进行交互,因此我们还需要一个连接工厂以及一个 Spring Redis 对话要用的 RedisTemplate
这些都是 Redis 缓存所必需的配置,把它们都放在自定义的 CachingConfigurerSupport
*/
@Bean
public CacheManager cacheManager(
@SuppressWarnings ( "rawtypes" ) RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
// cacheManager.setDefaultExpiration(60);// 设置缓存保留时间( seconds
return cacheManager;
}

//1. 项目启动时此方法先被注册成 bean spring 管理
@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;
}
}

新建controller
package com.redis.controller;

import com.redis.service.CityService;
import org.springframework.beans.factory.annotation. Autowired ;
import org.springframework.boot.autoconfigure. EnableAutoConfiguration ;
import org.springframework.web.bind.annotation. RequestMapping ;
import org.springframework.web.bind.annotation. ResponseBody ;
import org.springframework.web.bind.annotation. RestController ;

@RestController
@EnableAutoConfiguration
@RequestMapping ( "/query" )
public class CityController {

@Autowired
private CityService cityService ;

@ResponseBody
@RequestMapping ( "/findAll" )
public Object findAll() {
return cityService .selectAllCity();
}
}

在CityMapper.xml中加入
< select id ="selectAllCity" resultMap ="BaseResultMap" >
select
< include refid ="Base_Column_List" />
from city
</ select >
新建service
package com.redis.service;

import com.redis.domain.City;

import java.util.List;

public interface CityService {
List<City> selectAllCity();
}
实现service接口
package com.redis.service;

import com.redis.dao.CityMapper;
import com.redis.domain.City;
import org.springframework.beans.factory.annotation. Autowired ;
import org.springframework.cache.annotation. Cacheable ;
import org.springframework.stereotype. Service ;

import java.util.List;

@Service (value = "cityService" )
public class CityServiceImpl implements CityService {
@Autowired
private CityMapper cityMapper ;

@Override
@Cacheable (value = "all" , keyGenerator = "wiselyKeyGenerator" )
public List<City> selectAllCity() {
return cityMapper .selectAllCity();
}

}
查看redis数据库,发现第二次查询时间大幅减少,且出现配置中的缓存

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
项目描述 在上家公司自己集成的一套系统,用了两个多月的时间完成的:Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级开发系统 Springboot作为容器,使用mybatis作为持久层框架 使用官方推荐的thymeleaf做为模板引擎,shiro作为安全框架,主流技术 几乎零XML,极简配置 两套UI实现(bootstrap+layer ui),可以自由切换 报表后端采用技术: SpringBoot整合SSM(Spring+Mybatis-plus+ SpringMvc),spring security 全注解式的权限管理和JWT方式禁用Session,采用redis存储token及权限信息 报表前端采用Bootstrap框架,结合Jquery Ajax,整合前端Layer.js(提供弹窗)+Bootstrap-table(数据列表展示)+ Bootstrap-Export(各种报表导出SQL,Excel,pdf等)框架,整合Echars,各类图表的展示(折线图,饼图,直方图等),使用了layui的弹出层、菜单、文件上传、富文本编辑、日历、选项卡、数据表格等 Oracle关系型数据库以及非关系型数据库(Redis),Oracle 性能调优(PL/SQL语言,SQL查询优化,存储过程等),用Redis做中间缓存缓存数据 实现异步处理,定时任务,整合Quartz Job以及Spring Task 邮件管理功能, 整合spring-boot-starter-mail发送邮件等, 数据源:druid 用户管理,菜单管理,角色管理,代码生成 运行环境 jdk8+oracle+redis+IntelliJ IDEA+maven 项目技术(必填) Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis 数据库文件 压缩包内 jar包文件 maven搭建 Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统 http://localhost:/8080/login admin admin Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统Springboot+Mybatis-plus+ SpringMvc+Shiro+Redis企业级报表后台管理系统
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

古柏树下

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值