springboot 使用redis

安装redis教程:https://www.cnblogs.com/nongzihong/p/10190489.html

依赖:

    <!--配置redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>1.5.6.RELEASE</version>
        </dependency>

application.properties配置 我这里没有用yml格式

#配置redis
#Redis数据库索引(默认为0)
redis.hostName=127.0.0.1
redis.password=
#端口号

redis.port=6379
#客户端超时时间单位是毫秒 默认是2000
redis.timeout=10000

#最大空闲数

redis.maxIdle=300

#连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal

#redis.maxActive=600

#控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性

redis.maxTotal=300
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。

redis.maxWaitMillis=1000

#连接的最小空闲时间 默认1800000毫秒(30分钟)

redis.minEvictableIdleTimeMillis=300000

#每次释放连接的最大数目,默认3

redis.numTestsPerEvictionRun=1024

#逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1

redis.timeBetweenEvictionRunsMillis=30000

#是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个

redis.testOnBorrow=true

#在空闲时检查有效性, 默认false

redis.testWhileIdle=true

 

Spring boot config 配置

@Configuration
@EnableCaching
public class RedisCacheConfig {
    @Bean
    public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
        CacheManager cacheManager = new RedisCacheManager(redisTemplate);
        return cacheManager;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
        redisTemplate.setConnectionFactory(factory);
        // key序列化方式;(不然会出现乱码;),但是如果方法上有Long等非String类型的话,会报类型转换错误;
        // 所以在没有自己定义key生成策略的时候,以下这个代码建议不要这么写,可以不配置或者自己实现ObjectRedisSerializer
        // 或者JdkSerializationRedisSerializer序列化方式;
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();// Long类型不可以会出现异常信息;
        redisTemplate.setKeySerializer(redisSerializer);
        redisTemplate.setHashKeySerializer(redisSerializer);
        return redisTemplate;
    }

}

 

new RedisCacheManager(redisTemplate)没有此构造。报错解决方案在下面贴出

代码改一下:

 @Bean
    public CacheManager cacheManager(RedisConnectionFactory  factory) {
        RedisCacheManager redisCacheManager=RedisCacheManager.create(factory);
        return redisCacheManager;
    }

 

spring boot 的redis 工具类

@SuppressWarnings("unchecked")
@Component
public class RedisUtil {
@SuppressWarnings("rawtypes")

@Autowired
private RedisTemplate redisTemplate;

//写入redis后,防止乱码
@Autowired(required = false)
public void setRedisTemplate(RedisTemplate redisTemplate) {
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(stringSerializer);
this.redisTemplate = redisTemplate;
}

/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}

/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}

/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}

/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}

/**
* 读取缓存
*
* @param key
* @return
*/
public String get(final String key) {
Object result = null;
redisTemplate.setValueSerializer(new StringRedisSerializer());
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
if (result == null) {
return null;
}
return result.toString();
}

/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

public boolean hmset(String key, Map<String, String> value) {
boolean result = false;
try {
redisTemplate.opsForHash().putAll(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

public Map<String, String> hmget(String key) {
Map<String, String> result = null;
try {
result = redisTemplate.opsForHash().entries(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}

 

测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisUtilTest {
    @Autowired
    private RedisUtil redisUtil;

    @Test
    public void testSet() {
        String key = "key";
        System.out.println(redisUtil.get(key));
        String value = "sdd";
        redisUtil.set(key, value);
        System.out.println(redisUtil.get(key));
    }
}

截图:

 

第一次获取是null 正常的 因为还没添加到缓存里

 

看看cmd有没有:很好查询出来 没有毛病

 

 

如果cmd 查询redis命令行查看中文出现乱码

在redis-cli后面加上参数 --raw 即可

 

截图:

 

posted @ 2019-08-15 14:50  随★风  阅读(253)  评论(0编辑  收藏  举报