您的位置:首页 > 数据库 > Redis

SpringBoot中使用redis

2016-09-05 21:37 513 查看


redis配置文件

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.timeout=60000


redis配置类

package com.cachemodle;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConn {

private String host;

private int port;

private int timeout;

public String getHost() {
return host;
}

public void setHost(String host) {
this.host = host;
}

public int getPort() {
return port;
}

public void setPort(int port) {
this.port = port;
}

public int getTimeout() {
return timeout;
}

public void setTimeout(int timeout) {
this.timeout = timeout;
}

@Override
public String toString() {
return "Redis [localhost=" + host + ", port=" + port + ", timeout=" + timeout + "]";
}

}


在RedisConn类中注解@ConfigurationProperties(prefix = "spring.redis")的作用是读取springboot的默认配置文件信息中以spring.redis开头的信息。
package com.service;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;

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

/**
*
* @author sandsa redis cache service
*
*/

@Configuration
@EnableCaching
public class CacheService extends CachingConfigurerSupport {

@Autowired
private RedisConn redisConn;

/**
* 生产key的策略
*
* @return
*/

@Bean
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {

@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};

}

/**
* 管理缓存
*
* @param redisTemplate
* @return
*/

@SuppressWarnings("rawtypes")
@Bean
public CacheManager CacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// 设置cache过期时间,时间单位是秒
rcm.setDefaultExpiration(60);
Map<String, Long> map = new HashMap<String, Long>();
map.put("test", 60L);
rcm.setExpires(map);
return rcm;
}

/**
* redis 数据库连接池
* @return
*/

@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(redisConn.getHost());
factory.setPort(redisConn.getPort());
factory.setTimeout(redisConn.getTimeout()); // 设置连接超时时间
return factory;
}

/**
* redisTemplate配置
*
* @param factory
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(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);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}

}


这个缓存类继承的是CachingConfigurerSupport,它把刚才读取的配置文件信息的RedisConn类对象注入到这个类中。在这个类中keyGenerator()方法是key的生成策略,CacheManager()方法是缓存管理策略,redisConnectionFactory()是redis连接,redisTemplate()方法是redisTemplate配置信息,配置后使redis中能存储Java对象。


redis的工具类

package com.util;

import java.io.Serializable;
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.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

@Component
public class RedisUtils {

@SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate;

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

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

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

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

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

/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@SuppressWarnings("unchecked")
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
*/
@SuppressWarnings("unchecked")
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;
}

}


测试类

package com.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.modle.User;
import com.util.RedisUtils;

@RestController
@RequestMapping("/redis")
public class RedisCacheController {

@Autowired
private RedisUtils redisUtil;

@RequestMapping("/test")
public String getSessionId() {
redisUtil.set("123", "测试");
System.out.println("进入了方法");
String string = redisUtil.get("123").toString();
return string;
}

@RequestMapping("/student")
public User getStudent() {
User user = new User();
user.setId(001);
user.setAge(17);
user.setName("张三");
redisUtil.set("001", user);
return (User) redisUtil.get("001");
}

}


最后

最后启动springboot。访问http://localhost:8080/redis/student,能正常返回json信息
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  springboot redis