redis做springboot2.x的缓存

1.首先是引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 缓存依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--spring2.0集成redis所需common-pool2-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.4.2</version>
</dependency>
//下面的可要可不要
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

2. 在配置文件的东西(yaml or properties)

spring.redis.database=2 //第几个数据库,由于redis中数据库不止一个
spring.redis.host=localhost // 也可指定为127.0.0.1
spring.redis.port=6379 // 默认端口
spring.redis.password= // 默认为空

# springboot2.x以上如此配置,由于2.x的客户端是lettuce
# 单位要带上
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-wait=10000ms
spring.redis.lettuce.shutdown-timeout=100ms

# springboot1.x如此配置,由于1.x的客户端是jedis
#spring.redis.jedis.pool.max-active=8
#spring.redis.jedis.pool.min-idle=0
#spring.redis.jedis.pool.max-idle=8
#spring.redis.jedis.pool.max-wait=-1
#spring.redis.timeout=500

3. redisConfig里面的配置

/**
 * Author:delay_boy
 * Date:2019-08-07 18:43
 * Description:(描述)
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 这个方法是用来配置key的生成策略的
     * @return KeyGenerator
     */
    @Override
    @Bean
    public KeyGenerator keyGenerator() {

        return (o, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(o.getClass().getName()); // 类名
            sb.append(method.getName()); // 方法名
            for (Object param: params) {
                sb.append(param.toString()); // 参数名
            }
            logger.info("这里面的内容是:{}",sb.toString());
            return sb.toString();
        };

    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(3600)) // 60s缓存失效
            // 设置key的序列化方式
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
            // 设置value的序列化方式
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
            // 不缓存null值
            .disableCachingNullValues()
            .prefixKeysWith("SysUser");

        RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory)
            .cacheDefaults(config)
            .transactionAware()
            .build();

        logger.info("自定义RedisCacheManager加载完成");
        return redisCacheManager;
    }

    // key键序列化方式
    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }

    // value值序列化方式
    private GenericJackson2JsonRedisSerializer valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
}

4. 在service类里里面的设置

/**
 * Author:delay_boy
 * Date:2019-08-07 19:53
 * Description:(描述)
 */
@Service
public class SysUserService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private SysUserMapper sysUserMapper;

    @Cacheable(value = "user")
    public List<SysUser> findAllSysUser() {
        logger.info(sysUserMapper.selectAll().toString());
        return sysUserMapper.selectAll();
    }

    @Cacheable(value = "user")
    public SysUser findById(int id) {
        logger.info(sysUserMapper.selectByPrimaryKey(id).toString());
        return sysUserMapper.selectByPrimaryKey(id);
    }

    @CacheEvict("user")
    public void dropById(int id) {
        sysUserMapper.deleteByPrimaryKey(id);
    }

    @CachePut("user")
    public void updateUser(SysUser user) {
        sysUserMapper.updateByPrimaryKey(user);
    }

}

5.在controller里面的配置

@RestController
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/findall")
    public List<SysUser> findall() {
        return sysUserService.findAllSysUser();
    }
    @RequestMapping("/findbyid/{id}")
    public SysUser findbyid(@PathVariable("id") int id) {
        return sysUserService.findById(id);
    }
    @RequestMapping("/deletebyid/{id}")
    public String deletebyid(@PathVariable("id") int id) {
        sysUserService.dropById(id);
        return "ok";
    }

}

项目的demo已经上传到github中,可以自行下载测试

https://github.com/lkr-china/springboot-redis

springboot13(redis缓存)的更多相关文章

  1. 缓存工厂之Redis缓存

    这几天没有按照计划分享技术博文,主要是去医院了,这里一想到在医院经历的种种,我真的有话要说:医院里的医务人员曾经被吹捧为美丽+和蔼+可亲的天使,在经受5天左右相互接触后不得不让感慨:遇见的有些人员在挂 ...

  2. Windows下Redis缓存服务器的使用 .NET StackExchange.Redis Redis Desktop Manager

    Redis缓存服务器是一款key/value数据库,读110000次/s,写81000次/s,因为是内存操作所以速度飞快,常见用法是存用户token.短信验证码等 官网显示Redis本身并没有Wind ...

  3. 总结:如何使用redis缓存加索引处理数据库百万级并发

    前言:事先说明:在实际应用中这种做法设计需要各位读者自己设计,本文只提供一种思想.准备工作:安装后本地数redis服务器,使用mysql数据库,事先插入1000万条数据,可以参考我之前的文章插入数据, ...

  4. .NET基于Redis缓存实现单点登录SSO的解决方案[转]

    一.基本概念 最近公司的多个业务系统要统一整合使用同一个登录,这就是我们耳熟能详的单点登录,现在就NET基于Redis缓存实现单点登录做一个简单的分享. 单点登录(Single Sign On),简称 ...

  5. Redis缓存连接池管理

    import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.util.Assert;import ...

  6. ssm+redis 如何更简洁的利用自定义注解+AOP实现redis缓存

    基于 ssm + maven + redis 使用自定义注解 利用aop基于AspectJ方式 实现redis缓存 如何能更简洁的利用aop实现redis缓存,话不多说,上demo 需求: 数据查询时 ...

  7. Windows Azure Redis 缓存服务

    8月20日,Windows Azure (中国版)开始提供Redis缓存服务,比较国际版的Microsoft Azure晚了差不多一年的时间.说实话,微软真不应该将这个重要的功能delay这么长时间, ...

  8. .NET基于Redis缓存实现单点登录SSO的解决方案

    一.基本概念 最近公司的多个业务系统要统一整合使用同一个登录,这就是我们耳熟能详的单点登录,现在就NET基于Redis缓存实现单点登录做一个简单的分享. 单点登录(Single Sign On),简称 ...

  9. spring boot redis缓存JedisPool使用

    spring boot redis缓存JedisPool使用 添加依赖pom.xml中添加如下依赖 <!-- Spring Boot Redis --> <dependency> ...

随机推荐

  1. thinkphp5.0 insert添加数据

    首先引入文件:use think\Db; public function zhuce(){ $username = input("username");//手机号 $passwor ...

  2. 小程序onShow事件获取options方法

    微信小程序 onShow() 事件 onShow() 事件不接受参数,因此无法获取页面 url 传递过来的参数,只有 onLoad() 事件可以. onShow(options){ console.l ...

  3. 用 ArcMap 发布 ArcGIS Server Feature Server Feature Access 服务

    1. 安装Desktop, 2. 安装ArcGIS Server 3. 安装PostgreSQL 9.5 从 C:\Program Files (x86)\ArcGIS\Desktop10.5\Dat ...

  4. 深入浅出Mybatis系列六-objectFactory、plugins、mappers简介与配置

    注:本文转载自南轲梦 注:博主 Chloneda:个人博客 | 博客园 | Github | Gitee | 知乎 上篇文章<深入浅出Mybatis系列(五)---TypeHandler简介及配 ...

  5. 第四十九篇 入门机器学习——数据归一化(Feature Scaling)

    No.1. 数据归一化的目的 数据归一化的目的,就是将数据的所有特征都映射到同一尺度上,这样可以避免由于量纲的不同使数据的某些特征形成主导作用.   No.2. 数据归一化的方法 数据归一化的方法主要 ...

  6. 关于整合ssh中的细节03

    关于spring中提供的一些工具类和监听介绍 一.spring提供了一个HibernateTemplate类 ①HibernateTemplate类: 用于操作PO对象,类似Hibernate Ses ...

  7. FatMouse and Cheese HDU - 1078 dp

    #include<cstdio> #include<iostream> #include<cstring> using namespace std; int n,k ...

  8. 洛谷P1219 八皇后 我。。。。。。

    代码1    (学弟版) #include<bits/stdc++.h>using namespace std;int l[15];bool s[15];                  ...

  9. 【已解决】[求助] 求虚拟机防检测代码-VM虚拟机防游戏检测(虚拟机躲避游戏检测工具)

    [已解决][求助] 求虚拟机防检测代码 虚拟机如何躲过游戏等软件的检测,并能用vmware tools: 先把vmtools安装好后!   然后用这代码 monitor_control.restric ...

  10. UVa 12050 - Palindrome Numbers (回文数)

    A palindrome is a word, number, or phrase that reads the same forwards as backwards. For example, th ...