Redis在用户赞踩功能中的应用
用户点赞一条资讯,该资讯的点赞数量增加,点踩则踩数量增加,本项目的点赞点踩功能是通过redis数据库实现的,java操作redis数据库的工具类可用Jedis库。
1.需要在pom.xml中引入jedis的jar包:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
2.需要设计一个操作redis的业务类,Jedis对象的获取是通过jedis连接池JedisPool,把Jedis操作redis的方法写在业务层:
@Service
public class JedisAdapter implements InitializingBean {
/*InitializingBean接口为bean提供了初始化方法的方式,
它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。*/
private JedisPool pool=null;
private static final Logger logger = LoggerFactory.getLogger(JedisAdapter.class);
@Override
public void afterPropertiesSet() throws Exception {//在类初始化时执行此方法
// TODO Auto-generated method stub
pool=new JedisPool("localhost",6379);//创建Jedis连接池对象
}
public Jedis getJedis() {
return pool.getResource();
}
public void set(String key,String value) {
Jedis jedis=null;
try {
jedis=pool.getResource();
jedis.set(key, value);
}catch(Exception e) {
logger.error("redis异常:"+e.getMessage());
}finally {
if(jedis!=null) jedis.close();
}
}
public String get(String key) {
Jedis jedis=null;
try {
jedis=pool.g