在本地集成redis
文章目录
1配置redis基本信息 (resources下application.properties进行配置)
# redis 配置
spring.redis.host=localhost
spring.redis.password=
spring.redis.port=6379
spring.redis.database=1
2配置连接池参数(resources下 创建redis.properties)
# 声明连接池的参数
# 最大连接数 默认是 8 为负数表示无限制
spring.redis.jedis.pool.max-active=8
# 最大阻塞等待时间 默认为 -1
spring.redis.jedis.pool.max-wait=-1
# 连接池中 最大 和 最小 空闲连接数
spring.redis.jedis.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
# 连接超时时间
spring.redis.timeout=1000
3配置配置类 ,配置RedisTemplate(创建一个config包,在包下创建RedisConfig.java)
@Configuration
@PropertySource("classpath:redis.properties")
public class RedisConfig {
// 配置RedisTemplate对象
@Bean
public RedisTemplate<String,Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory){
RedisTemplate<String, Object> redisTemplate= new RedisTemplate<>();
// 自动读取配置到 redisConnectionFactory,然后配置到 redisTemplate 中
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 声明 对key 与 value的序列化方式
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setValueSerializer(genericFastJsonRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer);
return redisTemplate;
}
}
4创建一个Redisutil工具类(在util包下)
@Component
public class RedisUtil {
// 获取 redisTemplate
@Autowired
private RedisTemplate<String,Object> redisTemplate;
// 设置缓存
public void set(String key,Object value){
redisTemplate.opsForValue().set(key,value);
}
// 设置缓存 及其有效时间
public void set(String key,Object value,long timeout){
redisTemplate.opsForValue().set(key,value,timeout, TimeUnit.SECONDS);
}
// 获取缓存
public Object get(String key){
if(!redisTemplate.hasKey(key)){return null;}
return redisTemplate.opsForValue().get(key);
}
}
5创建service
public interface IRedisService {
void initData(String goodsId,Integer stockNum) ;
}
@Service
public class RedisService implements IRedisService {
@Autowired
private RedisUtil redisUtil;
@Override
public void initData(String goodsId, Integer stockNum) {
redisUtil.set(goodsId+"_count",stockNum);
}
}
6创建controller
@Controller
public class RedisController {
@Autowired
private IRedisService redisService;
@RequestMapping("initData")
@ResponseBody
public String initData(
@RequestParam("goodsId") String goodsId,
@RequestParam("stockNum") Integer stockNum){
redisService.initData(goodsId,stockNum);
return "success";
}
}