Java 在spring cloud中使用Redis,spring boot同样适用

1. 本地安装 redis 服务,官网下载。

2. 在开发中要使用 redis,首先要启动本地 redis 服务,启动后页面如下:

 

3. 在 spring boot 项目 pom.xml 文件中添加 Redis 需要的依赖包,可在生成 springboot 项目选择自动引入:

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

4. 在 application-dev.yml(spring cloud)/application.properties(spring boot) 配置文件中加入 Redis 的配置信息:

#此为 spring cloud 配置文件格式
spring:
  redis: database: 0 host: 127.0.0.1 port: 6379 password: timeout: 500 pool: max-active: 20 # 连接池最大连接数(使用负值表示没有限制 max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制 max-idle: 8 # 连接池中的最大空闲连接 min-idle: 0 # 连接池中的最小空闲连接
## 此为 spring boot 格式配置文件
# Redis 数据库索引(默认为 0)
spring.redis.database=0  
# Redis 服务器地址
spring.redis.host=127.0.0.1
# Redis 服务器连接端口
spring.redis.port=6379  
# Redis 服务器连接密码(默认为空)
spring.redis.password=  
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=20  
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8  
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0 
# 连接超时时间(毫秒)
spring.redis.timeout=500

5. 创建 Redis 的配置类,定义序列方式;配置了配置文件,spring boot 会自动加载 redis

package com.yf.microservice.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonAutoDetect;

/**

  • @Description: Redis 配置类
    */

@Configuration
public class RedisConfiguration {

    @Bean
    @SuppressWarnings(</span>"all"<span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 0, 255, 1)">public</span> RedisTemplate&lt;String, Object&gt;<span style="color: rgba(0, 0, 0, 1)"> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate</span>&lt;String, Object&gt; template = <span style="color: rgba(0, 0, 255, 1)">new</span> RedisTemplate&lt;String, Object&gt;<span style="color: rgba(0, 0, 0, 1)">();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer </span>= <span style="color: rgba(0, 0, 255, 1)">new</span> Jackson2JsonRedisSerializer(Object.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);
        ObjectMapper om </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> template;
    }

}

6. 定义一个简单的 redis 工具类,这里只给到简单的存取方法,Redis 封装了很多方法可使用 redisTemplate 调用,具体哪些方法查看 Redis 文档

package com.yf.microservice.web.rest.util;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**

  • Redis 工具类
    */
    @Component
    public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

      </span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
       * 判断key是否存在
       * </span><span style="color: rgba(128, 128, 128, 1)">@param</span><span style="color: rgba(0, 128, 0, 1)"> key 键
       * </span><span style="color: rgba(128, 128, 128, 1)">@return</span><span style="color: rgba(0, 128, 0, 1)"> true 存在 false不存在
       </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
      <span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">boolean</span><span style="color: rgba(0, 0, 0, 1)"> hasKey(String key) {
          </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
              </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> redisTemplate.hasKey(key);
          } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (Exception e) {
              e.printStackTrace();
              </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">;
          }
      }
    
      </span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
       * 普通缓存获取
       * </span><span style="color: rgba(128, 128, 128, 1)">@param</span><span style="color: rgba(0, 128, 0, 1)"> key 键
       * </span><span style="color: rgba(128, 128, 128, 1)">@return</span><span style="color: rgba(0, 128, 0, 1)"> 值
       </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
      <span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Object get(String key) {
          </span><span style="color: rgba(0, 0, 255, 1)">return</span> key == <span style="color: rgba(0, 0, 255, 1)">null</span> ? <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)"> : redisTemplate.opsForValue().get(key);
      }
      </span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
       * 普通缓存放入
       * </span><span style="color: rgba(128, 128, 128, 1)">@param</span><span style="color: rgba(0, 128, 0, 1)"> key 键
       * </span><span style="color: rgba(128, 128, 128, 1)">@param</span><span style="color: rgba(0, 128, 0, 1)"> value 值
       * </span><span style="color: rgba(128, 128, 128, 1)">@return</span><span style="color: rgba(0, 128, 0, 1)"> true成功 false失败
       </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
      <span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">boolean</span><span style="color: rgba(0, 0, 0, 1)"> set(String key, Object value) {
          </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
              redisTemplate.opsForValue().set(key, value);
              </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">;
          } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (Exception e) {
              e.printStackTrace();
              </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">false</span><span style="color: rgba(0, 0, 0, 1)">;
          }
      }
    

}

7. 前面使用 @Component 注解把 RedisUtils 类实例化放到 spring 容器中了,直接使用 @Autowired 获取对象使用,也可以直接使用 RedisTemplate 进行调用其他 redis 封装方法,参考上面写法

 @Autowired
 private RedisUtils redisUtil;

@Autowired
private RedisTemplate<String, Object> redisTemplate;

public String test() {
redisUtil.set(
"myName", "学不会丶");//存入 key -value
redisTemplate.opsForHash().putAll("map1", new
HashMap
<String, Object>());//存入 map 的方法,set,list 等方法查看 redis 文档
return redisUtil.get("myName").toString();//通过 key 取值
}