SpringBoot系列:Spring Boot集成redis

【Redis系列】Spring Boot 集成 Redis 实现缓存功能_springboot redis缓存配置 log.info(“key:{}在Redis中查不到数据.”, key);log.error(“Jedis delete操作出错”, e);log.error(“Jedis get操作出错”, e);log.error(“Jedis set操作出错”, e);* 根据key查询value值。* 设置key-value。* 获取Jedis资源。* 释放Jedis连接。 阅读详情

一、Redis

Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value的非关系型数据库,并提供多种语言的API。

由于Redis实现使用C语言编写,且采用了I/O多路复用,在响应速度与并发支持上都要优于关系型数据库,所以常被用来配合关系型数据库做高速缓存、共享Session、分布式锁、消息系统等。

Redis的重要性不言而喻,无论是其对于系统,还是对于自身技能而言,我们都应该好好掌握它,不过这里并不是Redis的教学,仅仅介绍Spring Boot如何集成·Redis。

二、redisTemplate方式使用Redis

要使用Redis,首先得引入Redis的依赖,Redis如此受欢迎,自然Spring Boot为它定制了专属的starter。

<!--redis依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

然后在配置文件中,我们需要在spring.redis节点下配置redis的ip、端口、密码、超时时间等等配置。

spring:
  redis:
    host: localhost
    port: 6379
    password: 1234
    timeout: 60000

在SpringBoot中,我们只要配置好对应的属性,就可以使用Redis了,且SpringBoot自动在容器中生成了一个RedisTemplate和一个StringRedisTemplate的Bean对象。但是,这个RedisTemplate的泛型是<Object,Object>,使用时需要频繁强转,编写代码并不是很方便,且这个RedisTemplate,key及value的序列化方式采用了JDK的序列化,会导致在库中的序列化数据看起来乱码。

一般业务中,我们常使用泛型为<String,Object>形式的RedisTemplate,因此我们自己来注入一个RedisTemplate<String,Object>的Bean。

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);

        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        redisTemplate.setValueSerializer(serializer);
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}

@Configuration表示这是一个配置类,@EnableCaching用于开启缓存。当配置类@Configuration和@EnableCaching一起注解时,会触发一个post processor,这会扫描每一个spring bean,查看是否已经存在注解对应的缓存。如果找到了,就会自动创建一个代理拦截方法调用,使用缓存的bean执行处理。

@Bean表示注入一个Bean对象,其中使用Jackson2JsonRedisSerializer来序列化和反序列化Redis的value值,StringRedisSerializer来序列化和反序列化redis的key值。需要一提的事,当多个系统使用同一个(实际通常是同一个Redis集群)时,需要保证每个系统的序列化和反序列化方式一致。

接着我们创建一个CacheDao,提供了set与get方法用于添加和获取缓存,缓存时间这里设置了一分钟。

@Repository
public class CacheDao {

    @Resource
    private RedisTemplate<String, Object> template;

    public void set(String key, Object value){
        System.out.println("添加缓存key->" + key);
        ValueOperations<String, Object> valueOperations = template.opsForValue();
        // 1分钟过期
        valueOperations.set(key, value, 1, TimeUnit.MINUTES);
    }

    public Object get(String key){
        System.out.println("获取缓存key->" + key);
        ValueOperations<String, Object> valueOperations = template.opsForValue();
        return valueOperations.get(key);
    }

}

那么缓存是否起到了作用呢,我们添加测试类UserApi,这是一个Controller,提供添加用户和获取用户的方法。

@RestController
@RequestMapping("user")
public class UserApi {

    @Autowired
    private UserService userService;

    /**
     * 添加用户
     * @param user
     */
    @PostMapping("addUser")
    public String addUser(User user){
        int id = userService.addUser(user);
        return "添加用户成功,主键id:" + id;
    }

    /**
     * 获取用户信息
     * @param id
     * @return
     */
    @GetMapping("getUser")
    public User getUser(@RequestParam(value = "id") int id){
        return userService.getUser(id);
    }

}

接下来是UserService,与之相对应的保存用户和获取用户的方法。IUserDao使用了mybatis,从数据库中获取,这里就不贴具体的代码了,而CacheDao则是上面展示过的,从缓存中读取。在添加用户的时候,我们将用户同时添加到缓存,或取用户的时候,我们将先从缓存中获取,如果缓存中不存在,则去数据库中查找,并同时进行缓存。

@Service
public class UserService {

    @Autowired
    private IUserDao userDao;

    @Autowired
    private CacheDao cacheDao;

    /**
     * 添加用户
     * @param user
     */
    public int addUser(User user){
        userDao.add(user);
        // 添加缓存
        cacheDao.set("user:id:" + user.getId(), user);
        return user.getId();
    }

    /**
     * 获取用户信息
     * @param id
     * @return
     */
    public User getUser(int id){
        // 从缓存中获取
        User user = (User)cacheDao.get("user:id:" + id);
        if(user == null){
            user = userDao.find(id);
            cacheDao.set("user:id:" + user.getId(), user);
        }
        return user;
    }

}

启动项目,下面我们通过swagger-ui进行测试(本项目已经集成了swagger2),我们添加张三、password的数据。
在这里插入图片描述
调用结果显示成功,且id为1。
在这里插入图片描述
然后我们去获取这条数据,使用/user/getUser接口,可以成功获取。
在这里插入图片描述
然后我们查看后台打印的信息,先是调用了缓存,然后又进行了查询数据库,诶……这好像不对啊,我刚刚添加时不是进行缓存了吗,为什么没有生效?
在这里插入图片描述
这是因为我在获取的时候已经超过了缓存生效时间1分钟,这时再次查询,就不会去数据库中查询了。
在这里插入图片描述

三、注解方式使用Redis

在Spring Boot项目中,注解满天飞,其实也可以使用注解形式进行缓存,该机制依赖于Spring CaChe,但是这种方式一般较少,因为其缓存机制依赖方法的入参和返回结果,缺乏一定的灵活性。

缓存的注解主要有@CachePut、@Cacheable、@CacheEvict,都作用于方法上。

  • @CachePut,添加缓存,key可以从入参中获取,value为方法返回值,注意并不是注解的value属性,value属性是用于表示缓存的空间,例如@CachePut(value=“user”, key="‘anno:user?’ + #user.id"),当然这必须要求方法有返回值,否则缓存的数据为空。
  • @Cacheable,既是获取,也是存储,存在缓存则从缓存中获取,不存在则进行缓存,缓存值为方法返回值
  • @CacheEvict表示清除缓存。
    在UserService中,我们新增updateUser更新用户,使用了@CacheEvict注解,getUserAnno获取用户,使用了@Cacheable。
 		/**
     * 修改用户信息
     * @param user
     */
    // @CachePut,每次都会进行缓存添加,缓存值为方法返回值,该方法无返回值无法使用
    // @CachePut(value="user", key="'anno:user:id:' + #user.id")
    // 直接删除缓存,下次获取重新查库
    @CacheEvict(value="user", key="'anno:user:id:' + #user.id")
    public void updateUser(User user){
        userDao.update(user);
    }


    /**
     * 获取用户信息,注解缓存
     * @param id
     * @return
     */
    // @Cacheable存在缓存则从缓存中获取,不存在则进行缓存,缓存值为方法返回值
    @Cacheable(value="user", key="'anno:user:id:' + #id")
    public User getUserAnno(int id){
        return userDao.find(id);
    }

多次调用getUserAnno方法,可以发现,仅第一遍进行了数据库访问,后面都没有调用数据库查询数据。我们接着再调用更新方法,然后在调用getUserAnno又从数据库中查取了。

源码地址:https://github.com/imyanger/springboot-project/tree/master/p10-springboot-redis

玩转 Spring boot 系列:(五)集成 redis 客户端 Jedis 前言: 玩转 Spring boot 系列:(一)使用 Idea 搭建 Spring boot Maven 多模块父子工程(图解) 玩转 Spring boot 系列:(二)配置多开发环境,集成druid数据源(图解) 玩转 Spring boot 系列:(三)集成mybatis,实现增删改查(图解) 玩转 Spring boot 系列:(四)mybatis 集成分页插件 pagehelper 并自定义分页结果集 springboot集成mybatis和自定义分页插件pagehelper... 阅读详情

相关推荐

SpringBoot系列:Spring Boot集成redis,新网银行java面试

一般业务中,我们常使用泛型为<String,Object>形式的RedisTemplate,因此我们自己来注入一个RedisTemplate<String,Object>的Bean。 @Configuration @EnableCaching public class CacheConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectio

m0_65320833的博客 182

SpringBoot之redis中常用的注解

目录 1. @Cacheable 2. @CachePut 3. @CacheEvict 1. @Cacheable 作用是主要针对方法配置,能够根据方法的请求参数对其结果进行缓存 主要参数说明: 1) value : 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如:@Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”}。 2) key :缓存的 key,可...

qq_52445443的博客 3248

SpringBoot2.x系列教程(六十八)Spring Boot集成Redis的坑,踩了!

最近项目中使用SpringBoot集成Redis,踩到了一个坑:从Redis中获取数据为null,但实际上Redis中是存在对应的数据的。是什么原因导致此坑的呢? 本文就带大家从SpringBoot集成Redis、所踩的坑以及自动配置源码分析来学习一下SpringBoot中如何正确的使用Redis。 SpringBoot集成Redis 在SpringBoot项目中只需在pom文件中引入Redis对应的starter,配置Redis连接信息即可进行使用了。pom依赖引入: <dependency>

程序新视界 2231

springboot集成redis使用注解

redis简介: Redis是当前比较热门的NOSQL系统之一,它是一个开源的使用ANSI c语言编写的key-value存储系统 (区别于MySQL的二维表格的形式存储。)。和Memcache类似,但很大程度补偿了Memcache的不 足。和Memcache一样,Redis数据都是缓存在计算机内存中,不同的是,Memcache只能将数据缓存到 内存中,无法自动定期写入硬盘,这就表示,一断电或重启,内存清空,数据丢失。所以Memcache的 应用场景适用于缓存无需持久化的数据。而Redis不同的是它会周期性

sjgllllll的博客 3799

Spring Boot 基于注解的 Redis 缓存使用详解

本篇文章主要介绍了Spring Boot 基于注解的 Redis 缓存使用详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

超越数据手册:深入Zynq XADC的DRP接口与PL端自定义采样逻辑

本文深入探讨Zynq-7000系列XADC模块的DRP接口机制与PL端自定义采样逻辑实现。通过硬件级多通道轮询、触发采样和实时校准技术,突破传统软件驱动限制,为高精度电压测量和通讯应用提供极致灵活性和响应速度。

xxx12的博客 770

概述springboot使用redis注解做缓存的基本操作

首先是添加方法,我们需要在方法上添加@CachePut注解,此注解用在添加以及更新的方法上,其中的key属性,是为了给redis中的key赋值,内容自定义,但一般为了key的唯一性,都取参数对象的id作为值,此处#user.id表示取方法阐述中的user的id属性作为值。我们准备五个方法用于测试,增删改查,以及全部查询,方法的返回值不能随便写,由于我们要添加缓存,添加到缓存中的数据是根据方法的返回值来操作的,所以除了删除的操作,方法的返回值都要给定成相应的对象。发现存储的信息变成了json格式,大功告成。

m0_71890428的博客 2747

2018南京大学计算机夏令营机试

1. Count number of binary strings without consecutive 1’s Given a positive integer n(3≤n≤90), count all possible distinct binary strings of length n such that there are no consecutive 1's . Examples...

climber16的博客 1万+

SpringBoot篇——SpringBoot集成Redis,详细教程,一篇搞定!

一、首先我们需要了解为什么我们非得要自定义redisTemplate呢?源码中的模板对于数据序列化是这么处理的二、编写流程在config包下新建一个类,命名为RedisConfig,将来关于Redis的配置都写在这个类中即可这段配置,如果我们真正项目中用到了redis,直接拿着用//Redis配置类,需要用@Configuration注解标记这个类是一个配置类//现在这个配置类是一个固定的模板,如果需要配置redis,直接拿走用即可。

我热爱学习,也乐于分享。无论是科技前沿的洞见,还是生活中的小技巧,我都会在这里与你分享。我相信,知识就是力量,而分享则能让这份力量得到更好的传递。 3225

MAX96712在车载摄像头系统中的带宽分配与传输能力计算解析

在计算摄像头带宽与传输接口的关系时,需要考虑视频流的像素分辨率、帧率、颜色深度等因素。以 MAX96712 这种 GMSL2 产品为例,它支持每个链路在正向方向以 3Gbps 或 6Gbps 的固定速率工作。

weixin_43199439的博客 3325

五步通关!宝塔Linux部署ASP.NET Core的魔法秘籍大公开!

摘要: 本文提供ASP.NET Core应用五步部署攻略,涵盖从环境配置到线上运行的完整流程: 1️⃣ 环境准备:安装宝塔面板、ASP.NET Core运行时及开放端口; 2️⃣ 应用发布:通过dotnet publish生成独立部署包并上传服务器; 3️⃣ Nginx配置:设置反向代理将域名请求转发至应用端口; 4️⃣ 进程守护:使用Supervisor确保应用持续运行; 5️⃣ HTTPS加密:通过宝塔快速申请SSL证书并解决验证路径冲突。 关键点: 强调权限设置(755)、端口开放及反向代理细节; 提

java专栏 969

【Redis系列】Spring Boot 集成 Redis 实现缓存功能

本文介绍了如何在 Spring Boot 项目中集成 Redis,并利用 Redis 实现缓存功能。文章包括配置 Redis 连接、使用 Jedis 和 RedisTemplate 两种方式进行操作的示例代码,并探讨了它们的优缺点。随着互联网应用的不断发展,对于数据的高效读写和缓存处理变得越来越重要。而 Redis 作为一款高性能的缓存数据库,被广泛应用于各种大型系统中。本文将介绍如何在 Spring Boot 项目中集成 Redis,并利用 Redis 实现缓存功能。

优快云站内信: https://i.youkuaiyun.com/#/msg/chat/qyj19920704 1万+

手把手教你学Simulink——基于经典PID控制的电机系统场景实例:BLDC电机PID电流控制策略仿真

*无刷直流电机(Brushless DC Motor, BLDC)**因其高效率、长寿命和低维护成本,在众多领域如家用电器、工业自动化、电动汽车等得到了广泛应用。为了实现对BLDC电机的有效控制,通常采用基于霍尔传感器或反电动势检测的换相技术,并结合电流闭环控制以提高系统的动态响应和稳定性。本教程将带你使用构建一个基于PID控制的BLDC电机电流控制策略仿真模型BLDC电机建模PID控制器设计与应用系统仿真与调试控制效果分析本文介绍了如何使用构建一个。

MHD0815的博客 196

32、Redis 7系列:Spring Boot集成Redis

32、Redis 7系列:Spring Boot集成Redis

Eyesmoon的博客 1247

基于改进YOLOv5的小目标检测 | 添加CBAM注意机制 + 更换Neck网络之BiFPN + 增加高分辨率检测头

本文针对图像中小目标难以检测的问题,提出了一种基于YOLOv5的改进模型。在主干网络中,加入CBAM注意力模块增强网络特征提取能力;在颈部网络部分,使用BiFPN结构替换PANet结构,强化底层特征利用;在检测头部分,增加高分辨率检测头,改善对于微小目标的检测能力。本文算法在无人机数据集VisDrone2019数据集上进行了多次对比实验,结果表明本文算法可以有效地检测小目标。🌈

小哥谈 2937

一种抑制undershoot/overshoot锐化算法介绍

一、USM 当增强图像的边缘、细节信息等高频信息时,图像的锐化视觉效果会得到较大提升。提高图像锐化的一种经典算法为非锐化掩码(UNsharp Masking)技术。该技术首先通过高通滤波并与缩放系数相乘,其结果再与原始图像相加,即可对高频信息进行增强。其主要的原理如下图所示: 其中,对图像进行高通滤波的另一种等效方法为:原始图像减去原始图像的低通滤波图像,其结果被称之为“掩码”。因此,上述的USM方法可以表示为: 原始图像减去原始图像低通滤波之后的图像得到掩码M。 2.掩...

大熊 4242

Spring Boot系列教程十二:Spring boot集成Redis

一.创建项目 项目名称为 “springboot_redis”,创建过程中勾选 “Web”,“Redis”,第一次创建Maven需要下载依赖包(耐心等待) 二.实现 properties配置文件中添加配置信息 ##########redis############ #redis的IP地址 spring.redis.host=localhost #redis的端口 ...

码农code之路 1万+

24、交通信号协调算法与模型解析

本文深入解析了交通信号协调中的关键算法与模型,包括多路径进展模型、MAXBAND网络系统模型和松弛启用带模型。这些模型通过合理安排相位序列、优化绿波带宽等方式,提高了交通运行的效率。文章还探讨了交通控制从单点控制向网络协调的发展趋势,分析了当前面临的挑战与机遇,并提出了未来研究方向,如借助信息技术和机器学习,深入研究交通网络的基本构成,以实现智能化和精准化的信号协调。

agile9scrum的博客 134

Spring Boot系列教程十三:Spring boot集成Sentinel Redis

前言 上一篇文章介绍了spring boot集成单点的redis,然而实际生产环境使用单点的redis风险很高,一旦宕机整个服务将无法使用,这篇文章介绍如何使用基于sentinel的redis高可用方案。 哨兵sentinel的地址如下: 192.168.12.194:26379 192.168.12.194:36379 192.168.12.194:46379 Redis的地址...

码农code之路 2万+

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Redis 7.x 系列【34】Spring Boot 集成

直接集成客户端,需要我们自己维护连接配置,获取客户端连接,再执行操作,最后还需要释放资源。Spring 提供了 Spring Data Redis 和 Spring Boot Data Redis Starter ,在 Spring Boot 环境中,可以很方便的连接并操作 Redis。

记录知识、锤炼自我 1975

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

Spring Boot系列教程九:Spring boot集成Redis

一.创建项目 项目名称为 “springboot_redis”,创建过程中勾选 “Web”,“Redis”,第一次创建Maven需要下载依赖包(耐心等待) 二.实现 properties配置文件中添加配置信息 1 ##########redis############ 2 3 #redis的IP地址 4 spring.redis.host=localhost...

weixin_30338743的博客 195

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring Boot 系列: 集成 Redis 数据库 分布式工具 Redisson 缓存 Spring Cache

Spring Boot 集成 Redis 数据库 分布式工具 Redisson 缓存 Spring Cache

weixin_46812727的博客 1014

Jackson 2.x 系列【29】Spring Boot 集成之 Redis 序列化/反序列化

Redis是一个常用的高性能非关系型内存数据库,接下来我们学习在Spring Boot中使用Redis时,集成基于Jackson的序列化/反序列化。

记录知识、锤炼自我 4339

Java直通车系列35【Spring Boot】(学习与其他技术集成Redis、RabbitMQ)

Java直通车系列正在连载更新中,更新的内容包括JSP、Spring MVC、Spring Boot、Spring Cloud完整学习资料以及详细解释代码示例,关注我,持续学习。

TEUTEU的博客 508
上一篇: SpringBoot系列:事务管理器Transactional
下一篇: SpringBoot系列:Spring Boot多数据源,jdbcTemplate方式
杨小格
博客等级 码龄10年 19粉丝 50原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值