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("all")
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
            template.setConnectionFactory(factory);
            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);
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            template.setKeySerializer(stringRedisSerializer);
            template.setHashKeySerializer(stringRedisSerializer);
            template.setValueSerializer(jackson2JsonRedisSerializer);
            template.setHashValueSerializer(jackson2JsonRedisSerializer);
            template.afterPropertiesSet();
            return 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;
 


        /**
         * 判断key是否存在
         * @param key 键
         * @return true 存在 false不存在
         */
        public boolean hasKey(String key) {
            try {
                return redisTemplate.hasKey(key);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        /**
         * 普通缓存获取
         * @param key 键
         * @return*/
        public Object get(String key) {
            return key == null ? null : redisTemplate.opsForValue().get(key);
        }
        /**
         * 普通缓存放入
         * @param key 键
         * @param value 值
         * @return true成功 false失败
         */
        public boolean set(String key, Object value) {
            try {
                redisTemplate.opsForValue().set(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
 }

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取值
    }

猜你喜欢

转载自www.cnblogs.com/laifw/p/10009144.html