由于项目中需要用到redis,使用的springboot框架,加之本身对ssm框架理解就不够深入,很多都很麻木的在application文件中配置,此类文件中没有可以使用的配置,则不会配置项目。为了能配置上redis。
- 首先,需要导入redis的jar包。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--redis客户端-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
- 配置一个redis.properties 由于是测试使用,故内容比较简单,放置在classpath下
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
- 提供一个config类
@Configuration
@PropertySource("classpath:redis.properties")
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Bean(name = "test")
public JedisPool jedisPoo(){
System.out.println("加载了");
return new JedisPool(host,port);
}
@Bean
public JedisPool jedisPoo2(){
System.out.println("加载了");
return new JedisPool(host,port);
}
}
这里前几段代码都是用来配置连接池的一些必须属性,从redis中获取,也可以直接通过赋值的方式。
之后的bean方法,其实只用一个就可以。
然后在需要用到连接池的做如下注释即可
@Repository
public class RedisDao {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JedisPool jedisPool;
//@Resource(name = "test")
//private JedisPool jedisPool;
}
这里解释为什么要用到两个@bean
首先,我对ssm框架了解不是特别充分,这里由于使用了@Repository和@Autowired注解之后,自然就配置完成了数据池,发现程序已经可以正常运行了。我就在想,如果以后碰到的程序需要多个redis池,如何解决,也就是出现两个@Bean,
其实只要给它们匹配一个名字
那需要使用使用的时候,如何指定,我常用的都是@Autowired,百度后发现可以用@Resource(name="")来指定
- @Autowired和@Resource的区别就在于,前者是自动的去扫描bean里面所有可以匹配类型的对象自动注入,而后者需要指定名字,当同一类型的bean只有一个的时候,前者明显更方便,但多个明显需要指定名称。当然后者也是去优先匹配类别,然后再去根据名字匹配
- 也就是说,当程序中有一个类型的bean 两种配置方式均可,当同类型有两个,必须使用后者
上述部分可能都特别简单qaq
补充:关于jedis的使用
然后对其get和set方法进行封装;从jedis池中获取jedis,执行get和set操作
@Repository
public class RedisDao {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Resource
private JedisPool jedisPool;
private RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class);
public Seckill getSeckill(long seckillId){
System.out.println(jedisPool);
try {
Jedis jedis = jedisPool.getResource();
try{
String key = "seckill:"+seckillId;
//查询redis , 反序列化为seckil对象
byte[] bytes = jedis.get(key.getBytes());
if (bytes!=null){
Seckill seckill = schema.newMessage();
ProtostuffIOUtil.mergeFrom(bytes,seckill,schema);
return seckill;
}
}finally {
jedis.close();
}
}catch (Exception e){
logger.error(e.getMessage(),e);
}
return null;
}
public String putSeckill(Seckill seckill){
try {
Jedis jedis = jedisPool.getResource();
try {
String key = "seckill:"+seckill.getSeckillId();
byte[] bytes = ProtostuffIOUtil.toByteArray(seckill,schema,LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
int timeout = 60*60;
String result = jedis.setex(key.getBytes(),timeout,bytes);
return result;
}finally {
jedis.close();
}
}catch (Exception e){
logger.error(e.getMessage(),e);
}
return null;
}
}