首页 > 编程知识 正文

spring整合redis详解,springboot内置消息队列

时间:2023-05-05 11:54:46 阅读:143954 作者:1890

一. Redis介绍

Redis是当前受欢迎的NOSQL系统之一,是一个用开源ANSI c语言编写的密钥值存储系统。 这与MySQL二维表格式的存储不同。 请参阅。 与Memcache相似,但在很大程度上弥补了Memcache的不足。 与Memcache一样,所有Redis数据都缓存在计算机的内存中,但Memcache只能将数据缓存在内存中,而不能自动定期写入硬盘。 这意味着关闭或重新启动后,内存将耗尽,数据将丢失。 因此,Memcache的APP应用程序场景适合于缓存不需要持久化的数据。 与Redis不同,它可以定期将更新的数据写入磁盘,并将修改操作写入添加的日志文件,从而实现数据的永久化。

Redis的特点:

1,Redis读取速度为110000次/s,写入速度为81000次/s

2、原子。 Redis的所有操作都是原子性的,Redis还支持将一些操作完全集成的原子性执行。

3 )支持多个数据结构(字符串); 列表(列表; hash (散列)、set (集合); zset (有序集合) )

4、持续化、集群部署

5、支持过期、支持事务、短信订阅

二、项目集成Redis

1、向common模块添加依赖关系

由于redis缓存是一个公共APP应用程序,因此在common模块下添加了依赖关系和配置,并在common模块pom.xml下添加了以下依赖关系

! --- redis---- dependencygroupidorg.spring framework.boot/groupidartifactidspring-boot-starter-data-redis/artifaact -- spring2.X集成redis所需的common-pool2----dependencygroupidorg.Apache.com mons/groupidartifactidcommons--

@ enable caching @ configurationpublicclassredisconfigextendscachingconfigurersupport { @ beanpublicredistemplatestring, objectredistemplate (redisconnectionfactoryfactory ) { RedisTemplateString,object template=newredistemplate ); redisserializerstringredisserializer=newstringredisserializer (; ml dwl2jsonredisserializerhxsdzxc2jsonredisserializer=newmldwl2jsonredisserializer (object.class ); 对象映射器om=new对象映射器(; om.set visibility (属性访问器. all,JsonAutoDetect.Visibility.ANY ); om.enabledefaulttyping (object mapper.default typing.non _ final ); hxsd zxc2jsonredisserializer.setobjectmapper (om; template.setconnectionfactory; //key序列化方式template.setkey serializer (redis serializer ); //value序列化template.setvalue serializer (hxsd zxc2jsonredisserializer ); //value hashmap序列化template.sethashvalueserializer (hxsd zxc2jsonredisserializer ); 返回模板; } @ beanpubliccachemanagercachemanager (redisconnectionfactoryfactory ) redisserializerstringredisserializer=newst ringr

edisSerializer(); mldwl2JsonRedisSerializer hxsdzxc2JsonRedisSerializer = new mldwl2JsonRedisSerializer(Object.class); //解决查询缓存转换异常的问题 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); hxsdzxc2JsonRedisSerializer.setObjectMapper(om); // 配置序列化(解决乱码的问题),过期时间600秒 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(600)) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(hxsdzxc2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; }}

3、在接口中添加redis缓存
由于首页数据变化不是很频繁,而且首页访问量相对较大,所以我们有必要把首页接口数据缓存到redis缓存中,减少数据库压力和提高访问速度。

3.1 Spring Boot缓存注解

(1)缓存@Cacheable
根据方法对其返回结果进行缓存,下次请求时,如果缓存存在,则直接读取缓存数据返回;如果缓存不存在,则执行方法,并把返回的结果存入缓存中。一般用在查询方法上。

查看源码,属性值如下:

(2)缓存@CachePut
使用该注解标志的方法,每次都会执行,并将结果存入指定的缓存中。其他方法可以直接从响应的缓存中读取缓存数据,而不需要再去查询数据库。一般用在新增方法上。

查看源码,属性值如下:

(3)缓存@CacheEvict
使用该注解标志的方法,会清空指定的缓存。一般用在更新或者删除方法上

查看源码,属性值如下:

3.2 启动redis服务

3.3连接redis服务可能遇到的问题
(1)关闭liunx防火墙
(2)找到redis配置文件, 注释一行配置

(3)如果出现下面错误提示

修改 protected-mode yes
改为
protected-mode no

在配置文件中添加

spring.redis.host=192.168.44.132spring.redis.port=6379spring.redis.database= 0spring.redis.timeout=1800000spring.redis.lettuce.pool.max-active=20spring.redis.lettuce.pool.max-wait=-1#最大阻塞等待时间(负数表示没限制)spring.redis.lettuce.pool.max-idle=5spring.redis.lettuce.pool.min-idle=0

使用方法,在类上添加注解就行了

Jedis使用Redis:

配置文件:

host=127.0.0.1port=6379maxTotal=50maxIdle=10

Jedis工具类:

package com.cxy.travel.util;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/** * Jedis工具类 */public final class JedisUtil { private static JedisPool jedisPool; static { //读取配置文件 InputStream is = JedisPool.class.getClassLoader().getResourceAsStream("jedis.properties"); //创建Properties对象 Properties pro = new Properties(); //关联文件 try { pro.load(is); } catch (IOException e) { e.printStackTrace(); } //获取数据,设置到JedisPoolConfig中 JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal"))); config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle"))); //初始化JedisPool jedisPool = new JedisPool(config, pro.getProperty("host"), Integer.parseInt(pro.getProperty("port"))); } /** * 获取连接方法 */ public static Jedis getJedis() { return jedisPool.getResource(); } /** * 关闭Jedis */ public static void close(Jedis jedis) { if (jedis != null) { jedis.close(); } }}

使用方法:

@Override public List<Category> findAll() { //1.从redis中查询 //1.1获取jedis客户端 Jedis jedis = JedisUtil.getJedis(); //1.2可使用sortedset排序查询 //Set<String> categorys = jedis.zrange("category", 0, -1); //1.3查询sortedset中的分数(cid)和值(cname) Set<Tuple> categorys = jedis.zrangeWithScores("category", 0, -1);// System.out.println("**********"+jedis.mget()); List<Category> cs = null; //2.判断查询的集合是否为空 if (categorys == null || categorys.size() == 0) { System.out.println("从数据库查询...."); //3.如果为空,需要从数据库查询,在将数据存入redis //3.1 从数据库查询 cs = categoryDao.findAll(); //3.2 将集合数据存储到redis中的 category的key for (int i = 0; i < cs.size(); i++) { jedis.zadd("category", cs.get(i).getCid(), cs.get(i).getCname()); } } else { System.out.println("从redis中查询....."); //4.如果不为空,将set的数据存入list cs = new ArrayList<Category>(); for (Tuple tuple : categorys) { Category category = new Category(); category.setCname(tuple.getElement()); category.setCid((int)tuple.getScore()); cs.add(category); } } return cs; }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。