Java微型博客系统——Redis实现防止重复登录和点赞的功能
久违地来更新一下项目。这次在之前的博客项目上加上了防止重复登录和文章的点赞功能。
Redis相关的代码写在一个新的provider中,模拟一个独立的服务器。同样将提供的服务注册在zookeeper中。该provider结构如下:
JedisUtils编写
JedisUtils是帮助获取redis连接的工具类。主要功能就是和redis建立连接。
package com.zhz.f.provider2.utils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.ResourceBundle;
public class JedisUtils {
public static JedisPool jp = null;
public static String host = null;
public static Integer port = null;
public static Integer MaxTotal = null;
public static Integer MaxIdle = null;
static {
//从properties中取出数据
ResourceBundle rb = ResourceBundle.getBundle("Jedis");
host = rb.getString("redis.host");
port = Integer.parseInt(rb.getString("redis.port"));
MaxTotal = Integer.parseInt(rb.getString("redis.MaxTotal"));
MaxIdle = Integer.parseInt(rb.getString("redis.MaxIdle"));
//新建配置类
JedisPoolConfig jpc = new JedisPoolConfig();
jpc.setMaxTotal(MaxTotal);//最大链接数
jpc.setMaxIdle(MaxIdle);//最大活动数
//新建Jedis池
jp = new JedisPool(jpc,host,port);
}
public static Jedis getJedis(){
return jp.getResource();
}
}
其中properties中存的是一些连接参数
redis.host=127.0.0.1
redis.port=6379
redis.MaxTotal=30
redis.MaxIdle=10
防止登录重复
Redis的业务
1.创建一个set类型的key“account”来保存登录过的账号。
2.当有新账号登录时,使用sadd添加,根据返回结果可以判定账号是否存在(0:账号已登录,添加失败;1:账号未登录,添加成功)
3.账号退出时,账号对应的将member删除
Redis接口
注意:接口是在共用的api包下的
package com.zhz.f.api.service;
public interface MyRedis {
boolean registerAccountInRedis(String account);
boolean logoutAccountInRedis(String account);
}
Redis接口实现
@DubboService
@Service
public class MyRedisService implements MyRedis {
private static final Jedis jedis = JedisUtils.getJedis();
@Override
public boolean registerAccountInRedis(String account