redis缓存数据库详解(四):redis与springboot整合

Redis详解 - SpringBoot整合Redis,RedisTemplate和注解两种方式的使用 本文主要讲 Redis 的使用,如何与 SpringBoot 项目整合,如何使用注解方式和 RedisTemplate 方式实现缓存。最后会给一个用 Redis 实现分布式锁,用在秒杀系统中的案例。 更多 Redis 的实际运用场景请关注开源项目 coderiver 项目地址:https://github.com/cachecats/coderiver 一、NoSQL 概述 什么是 NoSQL ?... 阅读详情

作为一个稀有的Java妹子,所写的所有博客都只是当作自己的笔记,留下证据自己之前是有用心学习的~哈哈哈哈(如果有不对的地方,也请大家指出,不要悄悄咪咪的不告诉我)

概述

在之前的一篇文章中介绍了redis的数据结构,以及每种数据结构对应的命令,这些命令是通过redis-cli连接redis服务器后,直接在控制台中输入的。所以本片文章介绍怎样实现在代码里操作redis。

一、引入依赖

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

二、配置属性

# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=

三、配置类

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * retemplate相关配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

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

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

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 对hash类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 对redis字符串类型数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 对链表类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 对无序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 对有序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}

四、配置服务类

@Component
public class RedisService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ListOperations listOperations;

    @Autowired
    private ZSetOperations zSetOperations;

    /**
     * 是否存在key
     * @param key
     * @return
     */
    public boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }

    /**
     *
     * @param pattern
     * @return
     */
    public Set<String> keys(String pattern){
        return redisTemplate.keys(pattern);
    }


    /**
     * 更换key的名字
     * @param oldKey
     * @param newKey
     */
    public void rename(String oldKey,String newKey){
        redisTemplate.rename(oldKey,newKey);
    }

    //########################String相关的操作########################
    /**
     * 添加数据
     * @param key
     * @param value
     */
    public void set(String key,String value){
        redisTemplate.opsForValue().set(key,value);
    }

    /**
     * 添加数据并设置过期时间
     * @param key
     * @param value
     * @param time
     */
    public void set(String key,String value,long time){
        redisTemplate.opsForValue().set(key,value,time,TimeUnit.MICROSECONDS);
    }

    /**
     * 获取数据
     * @param key
     * @return
     */
    public Object get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除数据
     * @param key
     */
    public void del(String key){
        redisTemplate.delete(key);
    }
    /**
     * 在对应key的value后面追加值
     * @param key
     * @param value
     */
    public void append(String key,String value){
        redisTemplate.opsForValue().append(key,value);
    }

    /**
     * 使对应key的value减少num或者1
     * @param key
     * @param num
     */
    public void decrement(String key,Long num){
        if(num==null){
            redisTemplate.opsForValue().decrement(key);
        }else {
            redisTemplate.opsForValue().decrement(key,num);
        }

    }

    /**
     * 使对应key的value增加num或者1
     * @param key
     */
    public void increment(String key,Object num){
        if(num==null){
            redisTemplate.opsForValue().increment(key);
        }else if(String.valueOf(num).contains(".")){
            redisTemplate.opsForValue().increment(key,Double.parseDouble(String.valueOf(num)));
        }else {
            redisTemplate.opsForValue().increment(key,Long.parseLong(String.valueOf(num)));
        }

    }

    /**
     * 获取多个key对应的value的集合
     * @param collection
     * @return
     */
    public List<String> multiGet(Collection collection){
        return redisTemplate.opsForValue().multiGet(collection);
    }

    /**
     * 一次性设置多个值
     * @param map
     */
    public void multiSet(Map<String,String> map){
        redisTemplate.opsForValue().multiSet(map);
    }

    /**
     * 获取key对应的value的字符串长度
     * @param key
     * @return
     */
    public long size(String key){
        return redisTemplate.opsForValue().size(key);
    }

    /**
     * 添加数据,并且返回value
     * @param key
     * @param value
     * @return
     */
    public String getAndSet(String key,String value){
        return redisTemplate.opsForValue().getAndSet(key,value);
    }

    /**
     * 当key不存在时添加数据,否则什么也不做
     * @param key
     * @param value
     * @return
     */
    public boolean setIfAbsent(String key,String value){
        return redisTemplate.opsForValue().setIfAbsent(key,value);
    }

    /**
     * 当key存在时,更新key的value
     * @param key
     * @param value
     * @return
     */
    public boolean setIfPresent(String key,String value){
        return redisTemplate.opsForValue().setIfPresent(key,value);
    }

    //########################list集合相关的操作########################
    /**
     * 在集合头部添加元素
     * @param key
     * @param value
     */
    public void lpush(Object key, Object value){
        listOperations.leftPush(key,value);
    }

    /**
     * 集合头部添加若干元素
     * @param key
     * @param collection
     */
    public void lpushAll(Object key,Collection collection){
        listOperations.leftPushAll(key,collection);
    }
    /**
     * 移除集合尾部元素
     * @param key
     */
    public void rpop(Object key){
        listOperations.rightPop(key);
    }

    /**
     * 获取集合中某下标的数据
     * @param key
     * @param index
     * @return
     */
    public Object index(Object key,long index){
        return listOperations.index(key,index);
    }

    /**
     * 获取集合从起始位置-终止位置的所有元素
     * @param key
     * @param start
     * @param end
     * @return
     */
    public List listRange(Object key,long start,long end){
        return listOperations.range(key,start,end);
    }

    /**
     * 返回集合的长度
     * @param key
     * @return
     */
    public long listSize(Object key){
        return listOperations.size(key);
    }
     /**
     * 阻塞的获取元素
     * @param key
     * @param time
     * @return
     */
    public Object brpop(Object key,long time){
        return listOperations.rightPop(key,time,TimeUnit.SECONDS);
    }


    //########################zset集合相关的操作########################
    /**
     * 添加元素
     * @param key
     * @param value
     * @param score
     */
    public void addZset(Object key,Object value,double score){
        zSetOperations.add(key,value,score);
    }

    public void incrementScore(Object key, Object value,double score){
        zSetOperations.incrementScore(key,value,score);
    }

    /**
     * 获取集合从起始位置-结束位置的所有元素
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set zsetRange(Object key,long start,long end){
        return zSetOperations.range(key,start,end);

    }

    /**
     * 获取集合的长度
     * @param key
     * @return
     */
    public long zSize(Object key){
        return zSetOperations.size(key);
    }

    /**
     * 移除元素
     * @param key
     * @param value
     */
    public void zsetRemove(Object key,Object value){
        zSetOperations.remove(key,value);
    }
}

五、示例

举例其中几个方法

1.set
 public void set(String key,String value,long time){
        redisTemplate.opsForValue().set(key,value);
    }
public void testRedisService() {
        redisService.set("test","test");
}

查询redis

127.0.0.1:6379> get test
"test"
2.increment

可以递增1,指定整数或者浮点数

public void increment(String key,Object num){
        if(num==null){
            redisTemplate.opsForValue().increment(key);
        }else if(String.valueOf(num).contains(".")){
            redisTemplate.opsForValue().increment(key,Double.parseDouble(String.valueOf(num)));
        }else {
            redisTemplate.opsForValue().increment(key,Long.parseLong(String.valueOf(num)));
        }

    }
//当age不存在时,直接初始化为0,并且将值增加指定数值
redisService.increment("age","5.9");

一开始没有age,查询redis

127.0.0.1:6379> get age
"5.9"
3.leftPush
//添加一个
public void lpush(Object key, Object value){
        listOperations.leftPush(key,value);
    }
//添加多个
public void lpushAll(Object key,Collection collection){
       listOperations.leftPushAll(key,collection);
}

redisService.lpush("mylist","haha");
List<String> list = new ArrayList<>();
list.add("xixi");
list.add("heihei");
redisService.lpushAll("mylist",list);

结果:

127.0.0.1:6379> lrange mylist 0 -1
1) "\"heihei\""
2) "\"xixi\""
3) "\"haha\""
4.rightPop
public void rpop(Object key){
        listOperations.rightPop(key);
    }
    
redisService.rpop("mylist");

结果:

127.0.0.1:6379> lrange mylist 0 -1
1) "\"heihei\""
2) "\"xixi\""
5.add
public void addZset(Object key,Object value,double score){
        zSetOperations.add(key,value,score);
    }
    
redisService.addZset("myset","hh",3);

结果:

127.0.0.1:6379> zrange myset 0 -1
1) "\"hh\""
6.remove
public void zsetRemove(Object key,Object value){
        zSetOperations.remove(key,value);
    }
 redisService.zsetRemove("myset","hh");

结果:

127.0.0.1:6379> zrange myset 0 -1
(empty list or set)
SpringBoot整合Redis缓存 Redis是一个高性能的Key-Value开源数据库,是一个非关系型的数据库,是为了解决高并发、高扩展,大数据存储等一系列的问题而产生的数据库解决方案。但它不能替代关系型数据库,只能作为特定环境下的扩充。... 阅读详情

相关推荐

SpringBoot整合Redis

由于redis内部不提供Java对象的存储格式,因此当操作的数据以对象的形式存在时,会进行转码,转换成字符串格式后进行操作,为了方便开发者使用基于字符串为数据操作,spring boot整合redis时提供了专门的API接口StringRedisTemplate,你可以理解为这是RedisTemplate的一种指定数据泛型的操作API。以上使用的数据存储时一个键对应一个值,如果要维护的数据过多,可以使用别的数据存储结构,例如hash,它是一种一个键可以存储多个数据的存储模型。

桑落兮的博客 2132

Redis讲解

一、redis使用 1.1 开启reids服务器端 1.2 开启redis客户端 基本使用(修改密码): 方法一:直接在客户端进行修改 查看当前的密码 config get requirepass 设置新的密码 config set requirepass 123456 再次查询密码时,出现:(error) NOAUTH Authentication required. 此时报错了!现在只需要密码认证就可以了: auth 123456 再次查询密码 127.0.0.1:6379>

weixin_38446891的博客 4349

SpringBoot+Mybatis整合Redis做MySQL的二级缓存

SpringBoot+Mybatis整合Redis做MySQL的二级缓存 第一次接触Redis有说的不对的地方欢迎大家指正,代码亲测可以食用。文章是在vscode中用markdown插件写完的,后来想想还是发在csdn上吧,就直接站题过来了,排版或者什么可能会有些问题,就先说这么多叭。 1. 什么是Redis Redis是一个NoSQL key-value型数据库,在项目中使用Redis主要考虑...

xiaoy990的博客 3477

springboot使用Redis作缓存使用入门

1.依赖与数据库设置 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId>

qq_41358574的博客 739

零基础教程:用Python给试卷照片自动切题(有道OCR+PIL完整流程)

本文为零基础用户提供了一套完整的Python自动化切题方案。通过调用有道OCR API识别试卷照片中的题目坐标,并利用PIL库进行精准裁剪,将杂乱的试卷图片自动分割为独立的题目图像。教程详细涵盖了环境搭建、图像预处理、API调用、坐标解析与批量处理全流程,帮助教育工作者和技术爱好者高效处理大量试卷,实现工作流程自动化。

grpc6streamer的博客 1172

Centos7 XFS(dm-0):Internal error XFS_WANT_CORRUPTED_GOTO

在k8s的道路上我们都是小白,每天启动虚机都会遇到各种各样的问题,这不。部署的k8s虚机启动发现操作系统启动异常,提示如下报错信息。进入/dev/mapper目录下,查询目录下路径信息。可以通过对文件系统进行修复操作,操作如下。重启完成后虚机恢复正常登录。

hedao0515的专栏 4582

SpringDataRedis知识概括

springboot-Data-Redis知识概括springboot-Data-Redis简介 springboot-Data-Redis简介

weixin_41005188的博客 2063

手把手教你:如何为自制的STM32H7飞控板适配PX4固件(基于NuttX)

本文详细介绍了如何为自制的STM32H7飞控板适配PX4固件,基于NuttX系统进行移植。从硬件设计规范到软件环境配置,再到PX4固件的移植与调试,提供了完整的实战指南。特别分享了如何复用FMU-v6u参考设计以节省开发时间,并解决了常见问题,帮助开发者快速实现高性能飞控系统的搭建。

weixin_27697385的博客 475

Spring Boot中使用Redis数据库

Spring Boot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis, MongoDB, Elasticsearch, Solr和Cassandra。 使用Redis Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库。 Redis官网 Redis中文社区 引入依赖 Spring Boot提供的数据访问框架Spring Data Redis基于Jedis。可以通

一个有情怀的程序猿博客 1474

iStore增强插件 如何重塑家庭网络与存储体验

本文深入解析了iStore增强插件如何重塑家庭数字生活体验。它通过集成智能流控、一键式文件共享、媒体服务器及智能家居网关等功能,将复杂的网络配置、存储管理与设备协同简化为图形化操作,有效解决了家庭网络卡顿、数据割裂与使用门槛高等核心痛点,让普通用户也能轻松打造高效、稳定、安全的家庭数字中枢。

prometheus9mon的博客 646

Windows平台高效BLE调试工具开发指南

本文为开发者提供了一份在Windows平台上开发高效BLE调试工具的详细指南。文章深入探讨了使用32feet.NET库进行蓝牙低功耗设备扫描、连接、数据通信及进阶功能开发的实战经验,旨在帮助开发者打造功能自定义、性能优化的专属调试利器,显著提升物联网和嵌入式设备的调试效率。

weixin_29201933的博客 255

SpringBoot 整合 redis 踩坑日记

SpringBoot 中除了了对常用的关系型数据库提供了优秀的自动化测试以外,对于很多 NoSQL 数据库一样提供了自动化配置的支持,包括:Redis, MongoDB, Elasticsearch, Solr 和 Cassandra。 01 整合redis Redis是一个速度非常快的非关系型数据库(non-relational database),它可以存储键(key)与5种不同类型的值(value)之间的映射(mapping),可以将存储在内存的键值对数据持久化到硬盘。可以使用复制特性来扩展读..

weixin_43919330的博客 1483

Dify沙盒容器部署实战:解决config.yaml缺失与系统调用权限问题

本文详细解析了Dify沙盒容器部署中的两大常见问题:config.yaml缺失与系统调用权限限制。通过实战步骤指导如何正确配置卷挂载解决`no such file or directory`错误,并深入讲解如何调整`allowed_syscalls`白名单应对`error: operation not permitted`权限问题,帮助开发者高效完成Dify容器化部署。

gg901的博客 920

深入SpringBoot:Redis缓存的集成与实现

SpringBoot整合Redis缓存一、缓存概念知识1、是什么缓存2、缓存的优缺点3、为什么使用缓存二、Redis概念知识1、Redis简介2、为什么用Redis作为缓存3、Redis 支持的数据类型4、Redis缓存常见问题1. 缓存穿透2. 缓存击穿3. 缓存雪崩4. 缓存一致性三、SpringBoot整合redis1、使用redis缓存1. 引入redis依赖2. 修改项目启动类3. 配置redis数据库4. 创建redis配置类5. 操作redis2、使用 SpringCache 的注解1. 注解

~ 1万+

基于STM32的智能电子秤设计毕业论文

摘要:本文设计了一款基于STM32F103C8T6的智能电子秤系统,通过HX711称重传感器实现高精度测量,采用OLED显示和矩阵键盘完成人机交互。系统包含重量采集、数据处理、单价设置、去皮清零及总价计算等功能模块,经测试测量误差小于0.1%,稳定性良好。研究实现了低成本、高可靠性的智能称重方案,为后续无线传输和AI算法集成奠定了基础。关键词:STM32;智能电子秤;HX711;OLED显示;矩阵键盘。

3254968421的博客 847

OpenClaw实战系列01:OpenClaw接入飞书机器人全接入指南 + Ollama本地大模型

通过 OpenClaw + Ollama + 飞书的组合,我们成功搭建了一个完全私有、免费、可定制的AI助理。它不仅能在日常聊天中提供帮助,还能通过OpenClaw强大的“技能”体系,真正去操作你的电脑、管理文件、甚至执行代码。这套方案将数据留在本地,既保证了隐私安全,又锻炼了动手能力。现在,去给你的AI助理添加更多酷炫的技能吧!

PeterPan的博客 1万+

SpringBoot整合redis缓存使用

一开始写增删改查基本都是直接对库操作,接口调用量少的时候,性能问题几乎不存在,但是数据量级上升之后,这些增删改查接口的压力也会大大上升,甚至会出现慢查询的情况,出现较大的延迟。这时候机智的小伙伴会使用索引,没错,索引可以解决一部分查询造成的性能问题。那么如何才能进一步提升查询的性能呢?对于读多写少的表可以使用缓存,那么将大大减少读取数据库的次数。 缓存常见的问题 1...

carson0408的博客 1万+

深度学习工具包 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")

一步一步实现SpringBoot整合Redis缓存

内含步骤很详细的demo,实现不了来找我

shang_0122的博客 7176

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

SpringBoot整合Redis配置MyBatis二级缓存

本文讲的是在SpringBoot项目中整合使用 Redis,并使用 Redis实现MyBatis 的二级缓存。使用场景就是在高并发的环境下,大量的查询直接落入DB,会导致数据库宕机,从而导致服务雪崩的情况。我们使用Redis作为MyBatis二级缓存,可以充分的缓解数据库的压力,从而达到服务的高可用。

微枫Micromaple的博客 1万+

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

redis整合SpringBoot实现数据缓存

redis进阶!redis在springboot项目中作为缓存的具体实现与使用,深刻认识redis'的其他作用。

Young_深情不及里子的博客 4079

Springboot整合Redis作为Mybatis的二级缓存

文章转载声明:转载请附带原文链接 0. 环境准备 以下是我本机的环境: SpringBoot2.3.x Mybatis3.x Redis5.x 本机或者服务器中搭建好redis环境,并启动成功!这里我用的是阿里云学生机上部署的redis5.x IDEA2020.x ,Eclipse2020也是可以的,编辑器选择无所谓! 1. 新版本springboot和IDEA编辑器踩坑(可以直接跳过该章节,遇到类似的错误再回头看) 如果您在实操过程中,使用的是IDEA2020 和springboot2.3.x 版.

兴趣使然的草帽路飞 1万+

SpringBoot集成Redis和配置Redis做缓存

Redis介绍 Redis是一个开源的、高性能的、基于键值对的缓存与存储系统,通过提供多种键值数据类型来适应不同场景下的缓存与存储需求,直观的存储结构使得通过程序交互十分简单。 Redis数据库中所有数据都存储在内存中,由于内存的读写速度远快于硬盘,因此Redis在性能上对比其他基于硬盘存储的数据库有非常明显的优势,而且Redis提供了对持久化的支持,即可以将内存中的数据异步写入到硬盘中,且不影...

打破沉默的博客 1万+

SpringBoot整合Redis实现缓存

SpringBoot整合Redis实现缓存 Redis redis简单来说就是一款基于内存的以键值对方式存储数据的非关系型数据库。 优点非常明显,由于存储在内存中,所以读取非常快。这种速度是mysql等数据库完全不能比拟的,所以我们常用redis作为缓存以减少对本地数据库的查询。 redis可以作为系统进程间的资源共享,例如使用redis实现spring session共享等等 关于redis的安装与操作这里就不多说了,百度有非常详细的教程,个人还是建议将redis部署在linux虚拟机或者服务器上。

Cwh_971111的博客 3554

springboot整合mybatis,mysql做数据库存储,redis做缓存

redis应用的场景 通过缓存来减少对关系型数据库的查询次数,减轻数据库压力。在执行DAO类的select***(), query***()方法时,先从Redis中查询有没有缓存数据,如果有则直接从Redis拿到结果,如果没有再向数据库发起查询请求取数据。   springboot已经集成了redis缓存,只需要在pom.xml中加载redis,然后通过注解即可完成配置。 首先在配置类...

wanderlustLee的博客 1万+

Springboot整合Redis

首先我们要知道Redis是什么:Redis一个NoSQL数据库,常用作缓存使用( cache ),用户访问应用,如果找数据的话会先访问redis,如果redis中有数据的话就直接返回发给用户,如果redis中没有的话我们再去查数据库,找到了数据之后一方面存到redis中,另一方面再反馈给用户,目的是说如果用户下次再访问类似的数据的话,redis中就有了。Redis如何启动:双击;客户端双击exit就退出了。

桂林电子科技大学 -芳 5042

Springboot整合redis注解做缓存

Springboot整合redis注解法做缓存 一般来说数据库的访问量不多的话,是完全不需要实现缓存的,但一旦用户多了起来,你的数据库又不支持缓存机制,及很容易发生宕机,所以我们用到了springboot集成的redis缓存来解决这个问题 主要Maven依赖 <dependencies> <dependency> <groupId>org....

kingtok的博客 3741
上一篇: redis缓存数据库详解(三):redis的持久化
下一篇: redis缓存数据库详解(五):分布式锁的实现
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值