首页 > 数据库 >SpringCloud中Redis

SpringCloud中Redis

时间:2022-12-04 14:57:13浏览次数:33  
标签:spring org redis springframework key SpringCloud import Redis

1.引入redis相关jar包

     pom 配置

<dependency>
 2     <groupId>org.springframework.boot</groupId>
 3     <artifactId>spring-boot-starter-data-redis</artifactId>
 4 </dependency>
 5 
 6 <dependency>
 7     <groupId>org.redisson</groupId>
 8     <artifactId>redisson</artifactId>
 9     <version>1.0.2</version>
10 </dependency>

2.配置Redis相关信息

     config.properties

   1 #redis 配置
   2 # Redis数据库索引(默认为0)
   3 spring.redis.database=${dev.spring.redis.database}
   4 # Redis服务器地址
   5 spring.redis.host=${dev.spring.redis.host}
   6 # Redis服务器连接端口
   7 spring.redis.port=${dev.spring.redis.port}
   8 # Redis服务器连接密码(默认为空)
   9 spring.redis.password=${dev.spring.redis.password}
   10 # 连接池最大连接数(使用负值表示没有限制)
   11 spring.redis.pool.max-active=${dev.spring.redis.pool.max-active}
   12 # 连接池最大阻塞等待时间(使用负值表示没有限制)
   13 spring.redis.pool.max-wait=${dev.spring.redis.pool.max-wait}
   14 # 连接池中的最大空闲连接
   15 spring.redis.pool.max-idle=${dev.spring.redis.pool.max-idle}
   16 # 连接池中的最小空闲连接
   17 spring.redis.pool.min-idle=${dev.spring.redis.pool.min-idle}
   18 # 连接超时时间(毫秒)
    19 spring.redis.timeout=${dev.spring.redis.timeout}

3.读取Redis链接信息 RedisConn

      redis 链接pojo

       1 @Component
        2 @ConfigurationProperties(prefix = "spring.redis")
        3 public class RedisConn {
        4 private String host;
        5 //prefix+参数名 对应于配置文件config.properties中的spring.redis.*信息
        6 private int port;
        7
       8 private int timeout;

4.RedisConfig

     RedisConfig

1 package com.sinosoft.product.service.redis;
2
3 import com.fasterxml.jackson.annotation.JsonAutoDetect;
4 import com.fasterxml.jackson.annotation.PropertyAccessor;
5 import com.fasterxml.jackson.databind.ObjectMapper;
6 import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.cache.CacheManager;
8 import org.springframework.cache.annotation.CachingConfigurerSupport;
9 import org.springframework.cache.annotation.EnableCaching;
10 import org.springframework.cache.interceptor.KeyGenerator;
11 import org.springframework.context.annotation.Bean;
12 import org.springframework.context.annotation.Configuration;
13 import org.springframework.data.redis.cache.RedisCacheManager;
14 import org.springframework.data.redis.connection.RedisConnectionFactory;
15 import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
16 import org.springframework.data.redis.core.RedisTemplate;
17 import org.springframework.data.redis.core.StringRedisTemplate;
18 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
19
20 import java.lang.reflect.Method;
21 import java.util.HashMap;
22 import java.util.Map;
23
24
25 @Configuration
26 @EnableCaching
27 public class RedisConfig extends CachingConfigurerSupport {
28 @Autowired
29 private RedisConn redisConn;
30
31 /**
32 * 生产key的策略
33 *
34 * @return
35 */
36
37 @Bean
38 @Override
39 public KeyGenerator keyGenerator() {
40 return new KeyGenerator() {
41
42 @Override
43 public Object generate(Object target, Method method, Object... params) {
44 StringBuilder sb = new StringBuilder();
45 sb.append(target.getClass().getName());
46 sb.append(method.getName());
47 for (Object obj : params) {
48 sb.append(obj.toString());
49 }
50 return sb.toString();
51 }
52 };
53
54 }
55
56 /**
57 * 管理缓存
58 *
59 * @param redisTemplate
60 * @return
61 */
62
63 @SuppressWarnings("rawtypes")
64 @Bean
65 public CacheManager CacheManager(RedisTemplate redisTemplate) {
66 RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
67 // 设置cache过期时间,时间单位是秒
68 rcm.setDefaultExpiration(60);
69 Map<String, Long> map = new HashMap<String, Long>();
70 map.put("test", 60L);
71 rcm.setExpires(map);
72 return rcm;
73 }
74
75 /**
76 * redis 数据库连接池
77 * @return
78 */
79
80 @Bean
81 public JedisConnectionFactory redisConnectionFactory() {
82 JedisConnectionFactory factory = new JedisConnectionFactory();
83 factory.setHostName(redisConn.getHost());
84 factory.setPort(redisConn.getPort());
85 factory.setTimeout(redisConn.getTimeout()); // 设置连接超时时间
86 return factory;
87 }
88
89 /**
90 * redisTemplate配置
91 *
92 * @param factory
93 * @return
94 */
95 @SuppressWarnings({ "rawtypes", "unchecked" })
96 @Bean
97 public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
98 StringRedisTemplate template = new StringRedisTemplate(factory);
99 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
100 ObjectMapper om = new ObjectMapper();
101 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
102 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
103 jackson2JsonRedisSerializer.setObjectMapper(om);
104 template.setValueSerializer(jackson2JsonRedisSerializer);
105 template.afterPropertiesSet();
106 return template;
107 }
108
109 }

5.RedisUtils  Redis工具类

   RedisUtil

1 package com.sinosoft.product.service.redis;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.data.redis.core.RedisTemplate;
5 import org.springframework.data.redis.core.ValueOperations;
6 import org.springframework.stereotype.Component;
7
8 import java.io.Serializable;
9 import java.util.Set;
10 import java.util.concurrent.TimeUnit;
11
12 @Component
13 public class RedisUtil{
14 @SuppressWarnings("rawtypes")
15 @Autowired
16 private RedisTemplate redisTemplate;
17
18 /**
19 * 批量删除对应的value
20 *
21 * @param keys
22 */
23 public void remove(final String... keys) {
24 for (String key : keys) {
25 remove(key);
26 }
27 }
28
29 /**
30 * 批量删除key
31 *
32 * @param pattern
33 */
34 @SuppressWarnings("unchecked")
35 public void removePattern(final String pattern) {
36 Set<Serializable> keys = redisTemplate.keys(pattern);
37 if (keys.size() > 0)
38 redisTemplate.delete(keys);
39 }
40
41 /**
42 * 删除对应的value
43 *
44 * @param key
45 */
46 @SuppressWarnings("unchecked")
47 public void remove(final String key) {
48 if (exists(key)) {
49 redisTemplate.delete(key);
50 }
51 }
52
53 /**
54 * 判断缓存中是否有对应的value
55 *
56 * @param key
57 * @return
58 */
59 @SuppressWarnings("unchecked")
60 public boolean exists(final String key) {
61 return redisTemplate.hasKey(key);
62 }
63
64 /**
65 * 读取缓存
66 *
67 * @param key
68 * @return
69 */
70 @SuppressWarnings("unchecked")
71 public Object get(final String key) {
72 Object result = null;
73 ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
74 result = operations.get(key);
75 return result;
76 }
77
78 /**
79 * 写入缓存
80 *
81 * @param key
82 * @param value
83 * @return
84 */
85 @SuppressWarnings("unchecked")
86 public boolean set(final String key, Object value) {
87 boolean result = false;
88 try {
89 ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
90 operations.set(key, value);
91 result = true;
92 } catch (Exception e) {
93 e.printStackTrace();
94 }
95 return result;
96 }
97
98 /**
99 * 写入缓存
100 *
101 * @param key
102 * @param value
103 * @return
104 */
105 @SuppressWarnings("unchecked")
106 public boolean set(final String key, Object value, Long expireTime) {
107 boolean result = false;
108 try {
109 ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
110 operations.set(key, value);
111 redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
112 result = true;
113 } catch (Exception e) {
114 e.printStackTrace();
115 }
116 return result;
117 }
118
119 }

 

 

6.Redis的使用

redis应用

 

1 //注入Redis的工具类

2
3 @Autowired
4 private RedisUtils redisUtil;
5
6 //判断Redis中是否存在对应key的信息,若存在则在reids中获取,若不存在从数据库查询,同时存入redis缓存中
7
8 if (redisUtil.exists(calcode+calFlag)) {
9 Log.info("从Redis缓存中获取产品计算编码:{" + calcode+calFlag + "}信息");
10 tLMCalCulate = (LMCalCulate) redisUtil.get(calcode+calFlag);
11 } else {
12 LMCalCulateExample tLMCalCulateExample=new LMCalCulateExample();
13 tLMCalCulateExample.createCriteria().andCalcodeEqualTo(calcode).andCalflgEqualTo(calFlag);
14 List<LMCalCulate> tListLMCalCulate = lMCalCulateMapper.selectByExample(tLMCalCulateExample);
15 if(null!=tListLMCalCulate && tListLMCalCulate.size()>0){
16 tLMCalCulate=tListLMCalCulate.get(0);
17 redisUtil.set(calcode+calFlag, tLMCalCulate);
18 }
19 }

 

标签:spring,org,redis,springframework,key,SpringCloud,import,Redis
From: https://www.cnblogs.com/codeLearn/p/16949821.html

相关文章

  • SpringCloud中Rabbitmq的使用
    1.pom配置,添加以来jar包 pom配置2.配置文件配置setting.properties3.rabbitmq消息发送一 发送消息4.rabbitmq消息接收一 接受消息5.rabbitmq发送二 发送mq消......
  • SpringCloud中Rabbitmq的使用
    1#RabbitMq2spring.rabbitmq.host=${dev.spring.rabbitmq.host}3spring.rabbitmq.port=${dev.spring.rabbitmq.port}4spring.rabbitmq.username=${dev.spring.ra......
  • SpringCloud中Redis的使用
    1.引入redis相关jar包 pom配置2.配置Redis相关信息 config.properties3.读取Redis链接信息RedisConn redis链接pojo4.RedisConfig RedisConfig5.RedisUtils......
  • Redis安装配置与Jedis访问数据库
    目录一、NOSQL概要二、Redis概要2.1、相关网站三、安装与配置Redis3.1、下载最新版的Redis3.2、添加环境变量3.3、启动服务器3.4、启动客户端3.5、测试并运......
  • 小练习-把MySQL数据库中的数据存入redis
    #pymysql、json、redis#1、连数据库,查到数据库里面所有的数据,游标类型要用pymysql.curosrs.DictCour#2、查到所有数据[{"id":1,"passwd":"49487dd4f94008a6110275e48a......
  • springboot中如何向redis缓存中存入数据
    packagecom.hope;importcom.fasterxml.jackson.core.JsonProcessingException;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.hope.domain.User;impor......
  • Redis--回顾提要
    一、写在前知识学了就忘!不用就忘!我太健忘!特此记录!用于复习打卡!Redis干就完事了!二、来辣!Redis做异步队列:一般list结构做队列,rpush生产消息,lpop消费消息,当lpop没有消......
  • 三阶段:第14周 分布式锁 案例实现 用redisson分布式锁
                              自动释放锁               ......
  • SpringBoot集成Redisson实现分布式锁单机版
    SpringBoot集成Redisson实战案例maven依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></d......
  • SpringBoot使用注解方式集成Redis缓存
    SpringBoot中Redis缓存注解Spring框架中所有的注解都是通过AOP的原理实现的,即Spring框架为我们创建代理对象,代理对象去实现注解的功能。所以当一个支持缓存的方法,在对象内部......