redis(redis集群)连接java,springboot

spring boot使用redis解决session双机问题 session双机问题在分布式系统中经常会遇到,也有挺多解决方案,列举几种: 1. 使用缓存(如redis)来解决 ① 可以自己重写session管理类,自己对session进行管理,这可能会比较麻烦一点,因为要考虑session续期问题,考虑不周全可能会有一些问题 ② 如果你使用spring boot,那么你有福了,spring boot有现成的解决方案,O(∩_∩)O~ 2.sessi... 阅读详情

1. springboot连接redis

使用redisTemplate该类可以存放任意类型的数据,但是该类型的数据必须实现序列,获取redis中对应的数据时,会进行反序列化。 如果使用RedisTemplate建议大家指定key,value,以及hashkey的序列化方式。

package com.tyt.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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
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.serializer.*;

import java.time.Duration;

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    //比如验证码
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600)) //缓存过期10分钟 ---- 业务需求。
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))//设置key的序列化方式
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) //设置value的序列化
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

2. springboot连接redis集群。

(1)哨兵

spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=192.168.213.188:26379

(2) 去中心化集群

spring.redis.cluster.nodes=192.168.213.188:8001,192.168.213.188:8002,192.168.213.188:8003,192.168.213.188:8004,192.168.213.188:8005,192.168.213.188:8006

3. springboot使用场景

(1)作为缓存。

1.为什么使用缓存?
   减少数据库的访问频率。 提高数据的访问率。

2.什么样的数据适合放入缓存?
    1.热点数据。 2. 修改频率比较低。3.安全系数低的。

缓存的原理:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8K1XWjz7-1619410496710)(.\Java连接redis,springboot整合redis,springboot连接redis集群,redis使用场景(作为缓存).assets\1618473577874-1619404121929.png)]

如何使用缓存

(1)搭建一个springboot+mp的工程

(2)引入redis相关的依赖

(3)配置redis

(4)service代码

package com.tyt.service;

import com.tyt.dao.DeptDao;
import com.tyt.entity.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class DeptService {

    @Resource
    private DeptDao deptDao;

    @Autowired
    private RedisTemplate redisTemplate;

    public Dept findById(Integer deptId){
        //1.从缓存中查询该数据
        Object o = redisTemplate.opsForValue().get("findById::" + deptId);
        if(o!=null){//表示从缓存中获取该数据
            return (Dept) o;
        }
        Dept dept = deptDao.selectById(deptId);
        redisTemplate.opsForValue().set("findById::"+deptId,dept);//把查询的结果放入缓存
        return dept;
    }


    //数据库和缓存同步问题!
    public int delete(Integer deptId){
        redisTemplate.delete("findById::"+deptId);//删除缓存
        int i = deptDao.deleteById(deptId);
        return i;
    }

    public int update(Dept dept){
        redisTemplate.delete("findById::"+dept.getDeptId());//删除缓存
        int i = deptDao.updateById(dept);
        redisTemplate.opsForValue().set("findById::"+dept.getDeptId(),dept);
        return i;
    }
}

上面这些代码每次都要写很多与业务无关的一些非业务代码!

(1)使用aop来解决---->动态代理(动态代理的实现模式基于JDK动态代理)
https://blog.youkuaiyun.com/qq_39470733/article/details/77315010
(2)基于spring的缓存注解。
package com.tyt;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@MapperScan(basePackages = "com.tyt.dao")
@EnableCaching //开启缓存的注解
public class SpringbootRedis02Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootRedis02Application.class, args);
    }

}



package com.tyt.service;

import com.tyt.dao.DeptDao;
import com.tyt.entity.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class DeptService {

    @Resource
    private DeptDao deptDao;

    //该注解作用:会先查询缓存,如果缓存存在,则不会执行代码块。 如果缓存中不存在则执行该方法,并把该方法的返回值存放到redis中
    @Cacheable(cacheNames = "findById",key = "#deptId")  //缓存的key值 为findById
    public Dept findById(Integer deptId){
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        Dept dept = deptDao.selectById(deptId);
        return dept;
    }


    //数据库和缓存同步问题!
    // beforeInvocation:是否在方法执行前就清空,缺省为 false,
    // 如果指定为 true,则在方法还没有执行的时候就清空缓存。缺省情况下,如果方法执行抛出异常,则不会清空缓存。
    @CacheEvict(cacheNames = "findById",key = "#deptId")
    public int delete(Integer deptId){
        int i = deptDao.deleteById(deptId);
        return i;
    }

    //这个注解是必须执行方法体,而且会把方法体执行的结果放入到缓存中。 如果发生异常则不操作缓存。
    @CachePut(cacheNames = "findById",key = "#dept.deptId")
    public Dept update(Dept dept){
        int i = deptDao.updateById(dept);
        return dept;
    }
}

(2)作为分布式锁

(3)作为点赞量videaId,0 incr(videaId),排行榜,转发量。

什么是计数器,如电商网站商品的浏览量、视频网站视频的播放数等。为了保证数据实时效,每次浏览都得给+1,并发量高时如果每次都请求数据库操作无疑是种挑战和压力。Redis提供的incr命令来实现计数器功能,内存操作,性能非常好,非常适用于这些计数场景 。 
关系型数据库在排行榜方面查询速度普遍偏慢,所以可以借助redis的SortedSet进行热点数据的排序。 在奶茶活动中,我们需要展示各个部门的点赞排行榜, 所以我针对每个部门做了一个SortedSet,然后以用户的openid作为上面的username,以用户的点赞数作为上面的score, 然后针对每个用户做一个hash, 通过zrangebyscore就可以按照点赞数获取排行榜,然后再根据username获取用户的hash信息,这个当时在实际运用中性能体验也蛮不错的。 

(4)限时业务的运用

redis中可以使用expire命令设置一个键的生存时间,到时间后redis会删除它。利用这一特性可以运用在限时的优惠活动信息、手机验证码等业务场景。 

使用redis作为分布式锁。

锁场景:

package com.tyt.distributedlock.service;

import com.tyt.distributedlock.dao.StockDao;
import com.tyt.distributedlock.entity.Stock;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class StockService02 {

    @Resource
    private StockDao stockDao;

    public String decrStock(Integer productId) {//synchronized () 同步方法    同步代码块
         //查询对应的id的库存
        synchronized (this) {
            Stock stock = stockDao.selectById(productId);
            if (stock.getNum() > 0) {
                //根据id修改库存
                stock.setNum(stock.getNum() - 1);
                stockDao.updateById(stock);
                System.out.println("库存剩余:" + (stock.getNum()));
                return "库存减少成功";
            } else {
                return "库存不足";
            }
        }
    }
}

这中锁不适合分布式项目。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-irs2A1XH-1619410496711)(.\Java连接redis,springboot整合redis,springboot连接redis集群,redis使用场景(作为缓存).assets\1618559864593-1619404221889.png)]

使用redis解决分布式锁的问题

package com.tyt.distributedlock.service;

import com.tyt.distributedlock.dao.StockDao;
import com.tyt.distributedlock.entity.Stock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Service
public class StockService {

    @Resource
    private StockDao stockDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public String decrStock(Integer productId) {//synchronized () 同步方法    同步代码块
        Boolean flag = redisTemplate.opsForValue().setIfAbsent("product::" + productId, "tyt",30, TimeUnit.SECONDS);
        //查询对应的id的库存
         if(flag) {//获取锁了
             try {
                 Stock stock = stockDao.selectById(productId);
                 if (stock.getNum() > 0) {
                     //根据id修改库存
                     stock.setNum(stock.getNum() - 1);
                     stockDao.updateById(stock); //异常发生
//                   int c=10/0;
                     System.out.println("库存剩余:" + (stock.getNum()));
                     return "库存减少成功";
                 } else {
                     return "库存不足";
                 }
             }catch (Exception e){
                  throw  new RuntimeException(e.getMessage());
             }
             finally {
                 redisTemplate.delete("product::" + productId);//释放锁资源 一定再finally
             }
         }else{
             System.out.println("服务器正忙请稍后再试..........");
             return "服务器正忙请稍后再试..........";
         }
    }
}

使用第三方组件redisson-----专门用于解决分布式问题。

       <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.13.4</version>
        </dependency>
   @Bean
    public RedissonClient getRedisson(){
        Config config=new Config();
        config.useSingleServer().setAddress("redis://192.168.213.188:6379");
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }
package com.tyt.distributedlock.service;

import com.tyt.distributedlock.dao.StockDao;
import com.tyt.distributedlock.entity.Stock;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Service
public class StockService {

    @Resource
    private StockDao stockDao;

    @Autowired
    private RedissonClient redisson; 

    public String decrStock(Integer productId) {//synchronized () 同步方法    同步代码块
        RLock lock = redisson.getLock("product::" + productId);//获取锁对象
        try {
            lock.tryLock(60,20,TimeUnit.SECONDS); //自己别设置时间。
            Stock stock = stockDao.selectById(productId);
            if (stock.getNum() > 0) {
                //根据id修改库存
                stock.setNum(stock.getNum() - 1);
                stockDao.updateById(stock); //异常发生
//                   int c=10/0;
//                Thread.sleep(35000);
                System.out.println("库存剩余:" + (stock.getNum()));
                return "库存减少成功";
            } else {
                return "库存不足";
            }
        }catch (Exception e){
             throw  new RuntimeException(e.getMessage());
        }
        finally {
            lock.unlock();
        }
    }
}

https://blog.youkuaiyun.com/qq_33732195/article/details/110920549?utm_term=redisson%E7%9C%8B%E9%97%A8%E7%8B%97%E6%9C%BA%E5%88%B6&utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2allsobaiduweb~default-0-110920549&spm=3001.4430

4. redis的面试题

1. redis缓存穿透? 如何避免缓存穿透。
   (1)数据库中没有该记录,而缓存中没有该记录。而这时有人恶意访问这种数据。 直接访问数据库。

解决方案:
   (1) 如果数据库中不存在该对象,则往缓存中放入一个空对象,并且设置很短的过期时间。
   
2.缓存的雪崩?如何避免?
  (1)再某一时刻,缓存中没有该记录,而这时会有大量的请求。这些请求打压到数据库。
       比如: 项目刚刚上线。------预访问热点数据。
             某一个缓存的时间到了。----> 失效时间是一个散列值。
             使用队列: ----->每次有限的请求访问数据库。
             

``

SpringSession实现Springboot+Redis会话同步 它还提供了透明的集成:HttpSession 允许以中立的方式替换应用程序容器(即 Tomcat)中的HttpSession,并支持在 Headers 中提供会话 ID 以与 RESTful API 一起使用。Session允许通过将对象存储在Web服务器的内存中在整个用户会话过程中保持任何对象。存储需要在整个用户会话过程中保持其状态的信息,例如登录信息或用户浏览Web应用程序时需要的其它信息。序容器的解决方案的情况下,可以轻松地支持集群会话。5.创建RedisConfig文件。 阅读详情

相关推荐

【5G NB-IoT NTN】3GPP R17 NB-IoT NTN介绍_nbiot ntn

你的支持,我的动力;祝各位前程似锦,offer不断,步步高升!!!” />你的支持,我的动力;祝各位前程似锦,offer不断,步步高升!!!更多资料点击此处获qu!!

2401_83703866的博客 3170

04-springboot与redis应用整合

1. 回顾 哈哈 2. 正文 1. springboot连接redis 2. springboot使用场景 3. springboot连接redis集群。 4. redis的常见面试题。 3. springboot连接redis 3.1阿里云方式连接redis集群 对于阿里云服务器,你需要将redis解压包中之前的文件下图;删除干净; 然后重启redis-server服务,使用阿里云的公网IP进行集群配置分配槽点; 使用本地虚拟机的使用虚拟机的IP进行集群配置分配槽点;不要使用127.0.0.1了,否则会

qq_40390762的博客 297

从零到一:Mx_yolo本地训练与K210部署实战指南

本文详细介绍了从零开始进行Mx_yolo本地模型训练到K210部署的全流程实战指南。涵盖环境配置、数据准备、模型训练与调优、模型转换及K210部署等关键步骤,并提供了常见问题解决方案和性能优化技巧,帮助开发者高效完成AI模型在嵌入式设备的落地应用。

weixin_29081163的博客 252

两个SpringBoot项目使用redis实现数据共享

导入依赖 <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.51</version> </dependency> <dependency>

qq_44690366的博客 1172

量化风控核心:信用评分卡模型的设计与迭代全流程

◦ 动态策略适配:根据评分卡结果动态调整风控流程——高分用户(>750分)秒级放款,中低分用户(600-700分)触发补充资料提交,低分用户(<600分)直接拒绝。◦ 特征有效性监控:每月计算特征IV值,对IV<0.1的低效特征(如“用户星座”)进行淘汰,同时引入新特征(如电商消费数据)。某城商行通过增量学习,评分卡PSI值长期稳定在0.1以下。◦ 数据筛选:整合征信数据(逾期记录、查询次数)、行为数据(消费频次、还款习惯),某银行评分卡纳入150+维度特征,覆盖用户偿债能力、意愿、稳定性等维度;

2501_91651383的博客 1485

泛微OA与金蝶云星空审批流程对接实战:从报销单到采购合同的完整指南

本文详细介绍了泛微OA与金蝶云星空审批流程的深度集成方案,涵盖从报销单到采购合同的完整对接指南。通过API层面的无缝连接,实现流程自动化、数据同源和权限联动,显著提升企业业务效率。文章还提供了环境配置、数据映射、接口安全等实用技巧,助力企业轻松完成系统对接。

weixin_29268637的博客 246

【案例实战】SpringBoot整合Redisson实现RedLock分布式锁同步

SpringBoot整合Redisson实现RedLock分布式锁同步

互联网小阿祥 3827

Ansys Lumerical 启动时出现 Error: Could not connect to Ansys license server specified at 1055@ 的另一种解决办法

昨天在关闭了中之后 就能正常打开 FDTD 了,结果今天想开启出现了同样的报错:我猜测昨天能启动的原因在于关闭之后要重启电脑,并且在重启之后我第一时间打开 lumerical 测试因此端口没有被占用,今天是在电脑启动之后一段时间才打开所以又遇到了端口占用的问题。

qq_51404184的博客 9571

六、Redis Java连接示例(连接池、哨兵、springboot、集群)

下面介绍用Java连接redis的一些例子,涉及管道、lua、哨兵连接、springboot连接的例子。 一、Java连接池连接(管道,lua) 加入如下依赖 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency&

zwj1030711290的优快云 2204

【基于51】红外寻迹智能小车 - 代码篇

这是一个基于C51单片机的红外巡线智能小车,是一个适合嵌入式单片机、C语言初学者练习的小Demo,文章提供完整的项目思路、免费的源代码。

ZER00000001的博客 3万+

银河麒麟V10等保加固清单:安全基线配置一篇搞定(附逐项检查表)

通过限制使用SSH直接以root身份登录,禁用公钥登录的方式加强SSH服务的安全性。更改SSH默认端口可在一定程度上防止被黑客使用大批量扫描方式攻击。通过修改SSH的配置文件限制可以使用SSH服务远程管理的主机。

信创运维工程师 · 银河麒麟 & 容器实战 | 金融生产环境迁移·等保加固 | 142篇原创·17万+阅读 822

基于springboot的Java连接Redis集群之Redis增删改查

1 新建一个maven的springboot工程,然后导入依赖 &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:sc...

wsc912406860的博客 1418

基于ESP32的室内空气质量检测系统开发

随着环境污染问题的日益严重,室内空气质量的监测变得越来越重要。室内空气质量的好坏直接影响到人们的健康,尤其是对于在封闭空间长时间待着的人群。为此,基于ESP32的室内空气质量检测系统应运而生。ESP32作为一款集成了Wi-Fi和蓝牙的高性能微控制器,为嵌入式开发提供了良好的平台,适用于构建各种智能硬件设备。本博客将详细介绍如何基于ESP32开发一个室内空气质量检测系统。系统可以实时监测空气中的温度、湿度、二氧化碳浓度、甲醛浓度等指标,并通过Wi-Fi将数据传输到云端或移动设备,方便用户随时查看空气质量情况。

2201_76125393的博客 833

SpringBoot java连接Redis集群

集群模式: 配置文件设置: ###REDIS (RedisProperties) redis集群配置 ######################################################## # Redis服务器地址 #spring.redis.host=127.0.0.1 # Redis服务器连接端口 #spring.redis.port=6379 # Redis服务器连...

DYZ的博客 1014

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

redis maven java_maven+springboot工程:Java连接Redis集群之Redis增删改查

今天技术之家陪你一起学习maven+springboot工程:Java连接Redis集群之Redis增删改查:1 新建一个maven的springboot工程,然后导入依赖xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">4.0.0org.spr...

weixin_39607798的博客 188

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

Java连接redis,springboot整合redis,springboot连接redis集群,redis使用场景及面试题

Java连接redis,springboot连接redis,springboot连接redis集群,redis使用场景及面试题1. springboot连接redis2. springboot连接redis集群。3. redis使用场景(1)作为缓存。(2)作为分布式锁(3)作为点赞量videaId,0 incr(videaId),排行榜,转发量。(4)限时业务的运用使用redis作为分布式锁。4. redis的面试题 1. springboot连接redis 使用redisTemplate该类可以存放任

vx_wszn7665的博客 219

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

redis04Java连接redis,springboot整合redis,springboot连接redis集群,redis使用场景(作为缓存),以及阿里云搭建集群连接去中心化集群出现的坑

Java连接redis—jedis 注意:阿里云要在redis.conf中开启:才能进行java连接redis protected-mode no 关闭protected-mode模式,此时外部网络可以直接访问

同一片天空 741

Redis分片集群模式以及整合SpringBoot

哨兵模式只有一个主节点,如果写操作频率过高,那么就会导致主节点出现宕机问题,就需要使用分片集群模式分片集群结构图:这些主从都会存在哨兵模式使用了分槽技术,默认集群槽的数量为16384个。而每个槽可以存放若干个数据。如果搭建redis集群模式会为主节点平均分配这些槽。

g474928663的博客 2393

java 连redis 集群_Springboot2.X集成redis集群(Lettuce)连接的方法

1. 新建工程,pom.xml文件中添加redis支持org.springframework.bootspring-boot-starter-data-redis2.配置application.propertiesspring.redis.cluster.nodes=127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0....

weixin_30043767的博客 333

JAVA连接redis集群源码_SpringBoot2.0 整合 Redis集群 ,实现消息队列场景

本文源码GitHub地址:知了一笑https://github.com/cicadasmile/middle-ware-parent一、Redis集群简介1、RedisCluster概念Redis的分布式解决方案,在3.0版本后推出的方案,有效地解决了Redis分布式的需求,当一个服务宕机可以快速的切换到另外一个服务。redis cluster主要是针对海量数据+高并发+高可用的场景。二、与Spr...

weixin_36166558的博客 265

redis集群

redis集群学习

qq_42218187的博客 487

Java连接redis + springboot整合redis+使用redis作为缓存

Java连接redis + springboot整合redis+java连接redis集群+springboot整合redis+常用指令+springboot使用redis集群模式+使用redis作为缓存(实现缓存/使用缓存注解实现)+使用自定义注解和aop实现缓存

不惧困难 顽强拼搏 803

springboot连接redis集群

开启redis服务和客户端 查看下当前redis的进程 [root@localhost ~]# ps -ef | grep redis 启动redis服务 [root@localhost ~]# cd /opt/redis-5.0.4 [root@localhost redis-5.0.4]# redis-server redis.conf 再查看下reids的服务进程 启动redis-cli [root@localhost redis-5.0.4]# redis-cli -h 192.168.2

程序猿杰哥的博客 2万+

java集成redis集群_Springboot2.X集成redis集群(Lettuce)连接的方法

前提:搭建好redis集群环境,搭建方式请看:1. 新建工程,pom.xml文件中添加redis支持org.springframework.bootspring-boot-starter-data-redis2.配置application.propertiesspring.redis.cluster.nodes=127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:638...

weixin_32516271的博客 160

java整合redis集群_Springboot2.X集成redis集群(Lettuce)连接的方法

前提:搭建好redis集群环境,搭建方式请看:1. 新建工程,pom.xml文件中添加redis支持org.springframework.bootspring-boot-starter-data-redis2.配置application.propertiesspring.redis.cluster.nodes=127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:638...

weixin_39805924的博客 186
上一篇: Redis的持久化方式
下一篇: rabbitmq的安装与简单实例
TYTvampire
博客等级 码龄7年 4粉丝 14原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值