日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

OpenFire源码学习之二十一:openfie对用户的优化(上)

發(fā)布時(shí)間:2023/12/18 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 OpenFire源码学习之二十一:openfie对用户的优化(上) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

用戶(hù)類(lèi)

優(yōu)化用戶(hù)主要是要解決用戶(hù)的連接量。已經(jīng)對(duì)用戶(hù)的訪問(wèn)速度和吞吐量。

預(yù)初始化

在前面的帶面中提出來(lái)了用戶(hù)的預(yù)初始化。這里就不在貼出來(lái)了。下面將redis用戶(hù)庫(kù)連接池處理貼出來(lái)UserJedisPoolManager

public class UserJedisPoolManager extends BasicModule{private static final Logger log = LoggerFactory.getLogger(UserJedisPoolManager.class);private static final String OF_ALL_USER = "select username, encryptedPassword, name, email, moblie, creationDate, modificationDate from ofuser";private static final String OF_USER_VCARD = "select username, vcard from ofvcard";private static final String OF_PRESENCE = "select username, offlinePresence, offlineDate from ofPresence";//private static final String REDIS_USER = "REDIS_USER";private static final Integer timeout = 1000*10;private static final int maxActive = 5000 * 10;private static final int maxIdle = 50;private static final long maxWait = (1000 * 100);private static JedisPool pool;private static XMPPServer loaclserver;private static JedisPoolConfig configs;public UserJedisPoolManager() {super("User redis manager");}private static JedisPoolConfig createConfig() {configs = new JedisPoolConfig();configs.setMaxActive(maxActive);configs.setMaxIdle(maxIdle);configs.setMaxWait(maxWait);configs.setTestOnBorrow(false);return configs;}private void createJedisPool() {RedisConfig redisConfig = loaclserver.getJedisConfDao().getRedisConfig("REDIS_USER");if (redisConfig != null) {+ " ,auto:" + redisConfig.getAuto());System.out.println(redisConfig.getAuto() .equals("") );pool = new JedisPool(createConfig(), redisConfig.getIp(), Integer.valueOf(redisConfig.getPort().trim()), timeout, redisConfig.getAuto().equals("") ? null : redisConfig.getAuto());Jedis jedis = pool.getResource();jedis.select(0);if(!jedis.exists("OFUSER:admin")) {DefaultAuthProvider dup = new DefaultAuthProvider();try {String password = dup.getPassword("admin");password = AuthFactory.encryptPassword(password);Map<String, String> map = new HashMap<String, String>();map.put("NAME", "admin");map.put("PASSWORD", password);map.put("CREATIONDATE", "0");map.put("MODIFICATIONDATE", "0");jedis.hmset("OFUSER:admin", map);} catch (UserNotFoundException e) {e.printStackTrace();}finally{pool.returnResource(jedis);} }}}private void poolInit() {createJedisPool();}public Jedis getJedis() {if (pool == null){poolInit();}Jedis jedis = pool.getResource();jedis.select(0);return jedis;}public void returnRes(Jedis jedis) {pool.returnResource(jedis);}@Overridepublic void initialize(XMPPServer server) {super.initialize(server);loaclserver = server;poolInit();log.info("UserManager By Redis: start init....");}public Collection<User> getAllUser() {Collection<User> users = new ArrayList<User>();PreparedStatement pstmt = null;Connection con = null;ResultSet rs = null;try {con = (Connection) DbConnectionManager.getConnection();pstmt = con.prepareStatement(OF_ALL_USER);rs = pstmt.executeQuery();while(rs.next()) {User user = new User();user.setUsername(rs.getString(1));user.setPassword(rs.getString(2));user.setName(rs.getString(3));user.setEmail(rs.getString(4));user.setMoblie(rs.getString(5));user.setCreationDate(rs.getString(6));user.setModificationDate(rs.getString(7));users.add(user);}}catch (Exception e) {log.info( e.getMessage());e.printStackTrace();}finally {DbConnectionManager.closeConnection(pstmt, con);}return users;}public Collection<UserVcard> getUserVcard() {Collection<UserVcard> userVcards = new ArrayList<UserVcard>();PreparedStatement pstmt = null;Connection con = null;ResultSet rs = null;try {con = (Connection) DbConnectionManager.getConnection();pstmt = con.prepareStatement(OF_USER_VCARD);rs = pstmt.executeQuery();while(rs.next()) {UserVcard user = new UserVcard();user.setUsername(rs.getString(1));user.setVcard(rs.getString(2));userVcards.add(user);}}catch (Exception e) {log.info( e.getMessage());e.printStackTrace();}finally {DbConnectionManager.closeConnection(pstmt, con);}return userVcards;}public Collection<Presence> getPresences() {......} }

在上面createJedisPool方法中預(yù)置了管理員的賬號(hào)。這是因?yàn)槲覀冃枰薷膐penfire的用戶(hù)認(rèn)證dao。也就是說(shuō)web控制臺(tái)的管理員。在登陸web頁(yè)面的時(shí)候,我們認(rèn)證也是先走redis驗(yàn)證的。

用戶(hù)認(rèn)證

用戶(hù)認(rèn)證,首先需要重新實(shí)現(xiàn)AuthProvider。Openfire當(dāng)中默認(rèn)使用的是DefaultAuthProvider來(lái)操作數(shù)據(jù)層。當(dāng)然他也提供了其他的方式實(shí)現(xiàn)接口,比如:HybridAuthProvider、JDBCAuthProvider、NativeAuthProvider、POP3AuthProvider等。

寫(xiě)完AuthProvider的Redis實(shí)現(xiàn)后,接下來(lái)需要基于Redis的用戶(hù)DAO。

下面是兩個(gè)類(lèi)的源碼清單:

RedisAuthProvider

public class RedisAuthProvider implements AuthProvider{private static final Logger log = LoggerFactory.getLogger(RedisAuthProvider.class);private static HmThreadPool threadPool = new HmThreadPool(3);......@Overridepublic void authenticate(String username, String password)throws UnauthorizedException, ConnectionException,InternalUnauthenticatedException {......}@Overridepublic void authenticate(String username, String token, String digest)throws UnauthorizedException, ConnectionException,InternalUnauthenticatedException {......}@Overridepublic String getPassword(String username) throws UserNotFoundException,UnsupportedOperationException {Jedis jedis = XMPPServer.getInstance().getUserJedis().getJedis();try {String pw = jedis.hmget("OFUSER:" + username, "PASSWORD").get(0);if (pw == null) {String userid = jedis.get("MOBILE:" + username);pw = jedis.hmget("OFUSER:" + userid, "PASSWORD").get(0);}return AuthFactory.decryptPassword(pw);} finally {XMPPServer.getInstance().getUserJedis().returnRes(jedis);}}@Overridepublic void setPassword(String username, String password)throws UserNotFoundException, UnsupportedOperationException {Jedis jedis = XMPPServer.getInstance().getUserJedis().getJedis();try {password = AuthFactory.encryptPassword(password);jedis.hset("OFUSER:" + username, "PASSWORD", password);} finally {XMPPServer.getInstance().getUserJedis().returnRes(jedis);}threadPool.execute(createTask(XMPPServer.getInstance().getJedisConfDao().getAuthProvider(), username, password));}@Overridepublic boolean supportsPasswordRetrieval() {// TODO Auto-generated method stubreturn true;}private static final String UPDATE_PASSWORD ="UPDATE ofUser SET encryptedPassword=? WHERE username=?";private Runnable createTask(final AuthProvider edp, final String username, final String password) { return new Runnable() { public void run() {try {//edp.setPassword(username, password);Connection con = null;PreparedStatement pstmt = null;try {con = DbConnectionManager.getConnection();pstmt = con.prepareStatement(UPDATE_PASSWORD);if (password == null) {pstmt.setNull(1, Types.VARCHAR);}else {pstmt.setString(1, password);}pstmt.setString(2, username);pstmt.executeUpdate();}catch (SQLException sqle) {throw new UserNotFoundException(sqle);}finally {DbConnectionManager.closeConnection(pstmt, con);}} catch (UserNotFoundException e) {log.info("UserNotFoundException: " + username);}} }; } }

用戶(hù)認(rèn)證寫(xiě)完后,要記得修改系統(tǒng)屬性表:ofProperty

provider.auth.className

org.jivesoftware.util.redis.expand.RedisAuthProvider


RedisUserProvider:

public class RedisUserProvider implements UserProvider{ ......public User loadUser(String username) throws UserNotFoundException {if(username.contains("@")) {if (!XMPPServer.getInstance().isLocal(new JID(username))) {throw new UserNotFoundException("Cannot load user of remote server: " + username);}username = username.substring(0,username.lastIndexOf("@"));}Jedis jedis = XMPPServer.getInstance().getUserJedis().getJedis();try {Map<String, String> map = jedis.hgetAll("OFUSER:" + username);String usernames = username;if (map.isEmpty()) {String userid = jedis.get("OFUSER:" + username);map = jedis.hgetAll("OFUSER:" + userid);if (map.isEmpty()) {return XMPPServer.getInstance().getJedisConfDao().getUserProvider().loadUser(username);}usernames = userid;}String name = map.get("NAME");String email = map.get("EMAIL");String mobile = map.get("MOBILE");String creationDate = map.get("CREATIONDATE");String modificationDate = map.get("MODIFICATIONDATE");User user = new User(usernames, name, email, mobile, new Date(Long.parseLong(creationDate.equals("0")||creationDate.equals("") ? StringUtils.dateToMillis(new Date()) : creationDate)), new Date(Long.parseLong(modificationDate.equals("0")||modificationDate.equals("") ? StringUtils.dateToMillis(new Date()) : modificationDate)));return user;} finally {XMPPServer.getInstance().getUserJedis().returnRes(jedis);}}public User createUser(String username, String password, String name, String email)throws UserAlreadyExistsException{return createUser(username, password, name, email, null);}public User createUser(String username, String password, String name, String email, String moblie)throws UserAlreadyExistsException{try {loadUser(username);// The user already exists since no exception, so:throw new UserAlreadyExistsException("Username " + username + " already exists");}catch (UserNotFoundException unfe) {Jedis jedis = XMPPServer.getInstance().getUserJedis().getJedis();Map<String, String> hash = new HashMap<String, String>();password = AuthFactory.encryptPassword(password);hash.put("PASSWORD", password);if (name != null && !"".equals(name))hash.put("NAME", name);if (email != null && !"".equals(email)) hash.put("EMAIL", email);if (moblie != null && !"".equals(moblie)) hash.put("MOBILE", moblie);Date now = new Date();hash.put("CREATIONDATE", StringUtils.dateToMillis(now));hash.put("MODIFICATIONDATE", StringUtils.dateToMillis(now));try {jedis.hmset("OFUSER:" + username, hash);} finally {XMPPServer.getInstance().getUserJedis().returnRes(jedis);}threadPool.execute(createTaskAddUser(username, null, password, name, email, moblie));return new User(username, name, email, moblie, now, now);}}private Runnable createTaskAddUser(final String username, final String password, final String encryptedPassword, final String name, final String email, final String moblie) {return new Runnable() {public void run () {.....}};}public void deleteUser(String username) {......}public int getUserCount() {int count = 0;Connection con = null;PreparedStatement pstmt = null;ResultSet rs = null;try {con = DbConnectionManager.getConnection();pstmt = con.prepareStatement(USER_COUNT);rs = pstmt.executeQuery();if (rs.next()) {count = rs.getInt(1);}}catch (SQLException e) {Log.error(e.getMessage(), e);}finally {DbConnectionManager.closeConnection(rs, pstmt, con);}return count;}public Collection<User> getUsers() {Collection<String> usernames = getUsernames(0, Integer.MAX_VALUE);return new UserCollection(usernames.toArray(new String[usernames.size()]));}public Collection<String> getUsernames() {return getUsernames(0, Integer.MAX_VALUE);}private Collection<String> getUsernames(int startIndex, int numResults) {......}public Collection<User> getUsers(int startIndex, int numResults) {Collection<String> usernames = getUsernames(startIndex, numResults);return new UserCollection(usernames.toArray(new String[usernames.size()]));}public void setName(String username, String name) throws UserNotFoundException {......}public void setEmail(String username, String email) throws UserNotFoundException {......}public void setCreationDate(String username, Date creationDate) throws UserNotFoundException {......}public void setModificationDate(String username, Date modificationDate) throws UserNotFoundException {......}public Set<String> getSearchFields() throws UnsupportedOperationException {return new LinkedHashSet<String>(Arrays.asList("Username", "Name", "Email"));}public Collection<User> findUsers(Set<String> fields, String query) throws UnsupportedOperationException {return findUsers(fields, query, 0, 100);}public Collection<User> findUsers(Set<String> fields, String query, int startIndex,int numResults) throws UnsupportedOperationException{......}/*** Make sure that Log.isDebugEnabled()==true before calling this method.* Twenty elements will be logged in every log line, so for 81-100 elements* five log lines will be generated* @param listElements a list of Strings which will be logged */private void LogResults(List<String> listElements) {......}@Overridepublic void setMoblie(String username, String moblie)throws UserNotFoundException {......} }

注意:這里有個(gè)moblie字段。在原來(lái)openfire用戶(hù)認(rèn)證表里面是沒(méi)有這個(gè)字段的。這里是本人新加的字段。方便手機(jī)登陸。看各自的頁(yè)面場(chǎng)景啦。



轉(zhuǎn)載于:https://www.cnblogs.com/huwf/p/4273347.html

總結(jié)

以上是生活随笔為你收集整理的OpenFire源码学习之二十一:openfie对用户的优化(上)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。