Chapter 2、不使用代理

版权声明:转载请注名出处 https://blog.csdn.net/meism5/article/details/90694053

为了满足两个需求

1、打印每个请求从开始到结束的耗时

2、校验某些请求的当前用户是否登录

可以在 Service 的实现类 ServiceImpl 中改造,增加耗时打印和校验登录代码。

//耗时统计
long start = System.currentTimeMillis();//计时开始
...
long end = System.currentTimeMillis();//计时结束
System.out.println("耗时:" + (end - start) + "毫秒");//打印耗时
		
/**
 * 模拟  当前用户是否登录
 */
private boolean checkIsLogined() {
	Random r = new Random();
	int i = r.nextInt(10);
	if (i % 2 == 0) {
		System.out.println("已登录");
		return true;
	}
	System.out.println("未登录");
	return false;
}

完整代码:

package constxiong.cxproxy.chapter2.service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 服务接口实现
 * @author ConstXiong
 * @date 2019-05-29 11:02:15
 */
public class ServiceImpl implements Service {

	@Override
	public boolean login(String username, String password) {
		long start = System.currentTimeMillis();//计时开始
		
		simulateDaOperation(100);
		System.out.println("用户名:" + username + ", 密码:" + password + "  登录成功");
		
		long end = System.currentTimeMillis();//计时结束
		System.out.println("耗时:" + (end - start) + "毫秒");//打印耗时
		
		return true;
	}

	@Override
	public Map<String, Object> getUserInfo(String username) {
		long start = System.currentTimeMillis();//计时开始
		
		Map<String, Object> userInfo = null;
		
		//校验是否登录
		if (checkIsLogined()) {
			userInfo = new HashMap<String, Object>();
			simulateDaOperation(150);
			userInfo.put("username", username);
			userInfo.put("sex", "男");
			userInfo.put("age", 18);
			System.out.println("用户名:" + username + ", 获取用户信息:" + userInfo);
		}
		
		long end = System.currentTimeMillis();//计时结束
		System.out.println("耗时:" + (end - start) + "毫秒");//打印耗时
		
		return userInfo;
	}
	
	
	
	/**
	 * 模拟  当前用户是否登录
	 */
	private boolean checkIsLogined() {
		Random r = new Random();
		int i = r.nextInt(10);
		if (i % 2 == 0) {
			System.out.println("已登录");
			return true;
		}
		System.out.println("未登录");
		return false;
	}

	/**
	 * 模拟数据库操作,休眠
	 * @param millis 毫秒数
	 */
	private void simulateDaOperation(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

未登录打印:

用户名:ConstXiong, 密码:123456  登录成功
耗时:100毫秒
未登录
耗时:1毫秒

已登录打印:

用户名:ConstXiong, 密码:123456  登录成功
耗时:100毫秒
已登录
用户名:ConstXiong, 获取用户信息:{sex=男, age=18, username=ConstXiong}
耗时:152毫秒

 

完整源码https://github.com/ConstXiong/xtools    cxproxy项目 chapter2

 

思考:

这种做法的缺点很明显:每次需求变更,核心的业务代码就需要改动,这块就得重测。
有没有做法可以不用修改核心业务代码,也能完成两个功能?有,使用代理。

猜你喜欢

转载自blog.csdn.net/meism5/article/details/90694053