提交 bdae627d 编写于 作者: Q qiurunze123

解决dubbo框架session无法同步问题

上级 7e54491e
...@@ -33,6 +33,8 @@ ...@@ -33,6 +33,8 @@
<artifactId>miaosha-common</artifactId> <artifactId>miaosha-common</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mybatis</groupId> <groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId> <artifactId>mybatis-spring</artifactId>
......
package com.geekq.admin.entity;
import com.geekq.common.utils.MD5.MD5Utils;
import com.geekq.common.utils.numcal.BidConst;
import lombok.Getter;
import lombok.Setter;
import org.apache.ibatis.type.Alias;
import java.math.BigDecimal;
/**
* 用户的帐户信息账户 一个LoginInfo 对应一个UserInfo对应一个Account
*
* @author 邱润泽
*/
@Getter
@Setter
@Alias("Account")
public class Account extends BaseDomain {
private static final long serialVersionUID = 6760287512112252557L;
private int version;
private String tradePassword; // 交易密码
private BigDecimal usableAmount = BidConst.ZERO; // 可用余额
private BigDecimal freezedAmount = BidConst.ZERO; // 冻结金额
private BigDecimal unReceiveInterest = BidConst.ZERO; // 账户待收利息
private BigDecimal unReceivePrincipal = BidConst.ZERO; // 账户待收本金
private BigDecimal unReturnAmount = BidConst.ZERO; // 账户待还金额
private BigDecimal remainBorrowLimit = BidConst.ZERO; // 账户剩余授信额度
private BigDecimal borrowLimitAmount; // 授信额度(当前还可以信用借款额度)
private String abstractInfo;//摘要信息用于防篡改检查;
public String getAbstractInfo() {//可用余额 + 冻结金额 + 账户神域的授权额度
return MD5Utils.MD5(usableAmount.add(freezedAmount)
.add(remainBorrowLimit).toString());
}
public boolean checkAbstractInfo() {//可用余额 + 冻结金额 + 账户神域的授权额度
return MD5Utils.MD5(
usableAmount.add(freezedAmount).add(remainBorrowLimit)
.toString()).equals(abstractInfo);
}
public BigDecimal getTotalAmount() {
return usableAmount.add(freezedAmount).add(unReceivePrincipal);
}
public void addUseableAmount(BigDecimal amount) {
this.usableAmount = this.usableAmount.add(amount);
}
public void addFreezedAmount(BigDecimal amount) {
this.freezedAmount = this.freezedAmount.add(amount);
}
public static Account empty(Long id) {
Account account = new Account();
account.setId(id);
account.setBorrowLimitAmount(BidConst.DEFALUT_BORROWLIMITAMOUNT);
account.setRemainBorrowLimit(BidConst.DEFALUT_BORROWLIMITAMOUNT);
return account;
}
}
package com.geekq.admin.service;
import com.geekq.admin.entity.Account;
import java.util.List;
public interface IAccountService {
void update(Account account);
Account get(Long id);
void recreateAbstractInfo();
List<Account> listAll();
}
package com.geekq.admin.service;
import com.geekq.admin.entity.Userinfo;
public interface IUserService {
void update(Userinfo userinfo);
Userinfo get(Long id);
boolean bindPhone(String phoneNumber, String verifyCode);
/**
* 修改基本信息
* @param userinfo
*/
void updateBasicInfo(Userinfo userinfo);
}
package com.geekq.admin.service;
import com.geekq.admin.entity.Logininfo;
import java.util.Map;
public interface RedisCacheStorageService<K, V> {
/**
* 在redis数据库中插入 key 和value
*
* @param key
* @param value
* @return
*/
boolean set(String key, V value);
Logininfo get(String key);
}
...@@ -11,6 +11,20 @@ ...@@ -11,6 +11,20 @@
<packaging>war</packaging> <packaging>war</packaging>
<dependencies> <dependencies>
<!-- jedis依赖 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.4.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency> <dependency>
<groupId>com.geekq</groupId> <groupId>com.geekq</groupId>
<artifactId>miaosha-admin-api</artifactId> <artifactId>miaosha-admin-api</artifactId>
...@@ -58,7 +72,11 @@ ...@@ -58,7 +72,11 @@
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId> <artifactId>spring-aspects</artifactId>
</dependency> </dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- Mybatis --> <!-- Mybatis -->
<dependency> <dependency>
<groupId>org.mybatis</groupId> <groupId>org.mybatis</groupId>
......
package com.geekq.admin.mapper;
import com.geekq.admin.entity.Account;
import java.util.List;
public interface AccountMapper {
int deleteByPrimaryKey(Long id);
int insert(Account record);
Account selectByPrimaryKey(Long id);
List<Account> selectAll();
int updateByPrimaryKey(Account record);
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.geekq.admin.mapper.AccountMapper" >
<resultMap id="BaseResultMap" type="com.geekq.admin.entity.Account" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="tradePassword" property="tradePassword" jdbcType="VARCHAR" />
<result column="usableAmount" property="usableAmount" jdbcType="DECIMAL" />
<result column="freezedAmount" property="freezedAmount" jdbcType="DECIMAL" />
<result column="borrowLimitAmount" property="borrowLimitAmount" jdbcType="DECIMAL" />
<result column="version" property="version" jdbcType="INTEGER" />
<result column="unReceiveInterest" property="unReceiveInterest" jdbcType="DECIMAL" />
<result column="unReceivePrincipal" property="unReceivePrincipal" jdbcType="DECIMAL" />
<result column="unReturnAmount" property="unReturnAmount" jdbcType="DECIMAL" />
<result column="remainBorrowLimit" property="remainBorrowLimit" jdbcType="DECIMAL" />
<result column="abstractInfo" property="abstractInfo" />
</resultMap>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
delete from account
where id = #{id,jdbcType=BIGINT} and version=#{version}
</delete>
<insert id="insert" parameterType="com.geekq.admin.entity.Account" keyProperty="id" >
insert into account (id,tradePassword, usableAmount, freezedAmount,
borrowLimitAmount, version, unReceiveInterest,
unReceivePrincipal, unReturnAmount, remainBorrowLimit,abstractInfo)
values (#{id},#{tradePassword,jdbcType=VARCHAR}, #{usableAmount,jdbcType=DECIMAL}, #{freezedAmount,jdbcType=DECIMAL},
#{borrowLimitAmount,jdbcType=DECIMAL}, 0, #{unReceiveInterest,jdbcType=DECIMAL},
#{unReceivePrincipal,jdbcType=DECIMAL}, #{unReturnAmount,jdbcType=DECIMAL}, #{remainBorrowLimit,jdbcType=DECIMAL},#{abstractInfo})
</insert>
<update id="updateByPrimaryKey" parameterType="com.geekq.admin.entity.Account" >
update account
set tradePassword = #{tradePassword,jdbcType=VARCHAR},
usableAmount = #{usableAmount,jdbcType=DECIMAL},
freezedAmount = #{freezedAmount,jdbcType=DECIMAL},
borrowLimitAmount = #{borrowLimitAmount,jdbcType=DECIMAL},
version = version+1,
unReceiveInterest = #{unReceiveInterest,jdbcType=DECIMAL},
unReceivePrincipal = #{unReceivePrincipal,jdbcType=DECIMAL},
unReturnAmount = #{unReturnAmount,jdbcType=DECIMAL},
remainBorrowLimit = #{remainBorrowLimit,jdbcType=DECIMAL},
abstractInfo=#{abstractInfo}
where id = #{id,jdbcType=BIGINT} and version=#{version}
</update>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
select id, tradePassword, usableAmount, freezedAmount, borrowLimitAmount, version,
unReceiveInterest, unReceivePrincipal, unReturnAmount, remainBorrowLimit,abstractInfo
from account
where id = #{id,jdbcType=BIGINT}
</select>
<select id="selectAll" resultMap="BaseResultMap" >
select id, tradePassword, usableAmount, freezedAmount, borrowLimitAmount, version,
unReceiveInterest, unReceivePrincipal, unReturnAmount, remainBorrowLimit,abstractInfo
from account
</select>
</mapper>
\ No newline at end of file
package com.geekq.admin.redis;
import com.alibaba.fastjson.JSON;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.ResourceBundle;
public class RedisClient {
/**
* 池化管理jedis链接池
*/
public static JedisPool jedisPool;
static {
//读取相关的配置
ResourceBundle resourceBundle = ResourceBundle.getBundle("redis");
int maxActive = Integer.parseInt(resourceBundle.getString("redis.pool.maxActive"));
int maxIdle = Integer.parseInt(resourceBundle.getString("redis.pool.maxIdle"));
int maxWait = Integer.parseInt(resourceBundle.getString("redis.pool.maxWait"));
String ip = resourceBundle.getString("redis.ip");
int port = Integer.parseInt(resourceBundle.getString("redis.port"));
JedisPoolConfig config = new JedisPoolConfig();
//设置最大连接数
config.setMaxTotal(maxActive);
//设置最大空闲数
config.setMaxIdle(maxIdle);
//设置超时时间
config.setMaxWaitMillis(maxWait);
//初始化连接池
jedisPool = new JedisPool(config, ip, port);
}
/**
* 向缓存中设置字符串内容
*
* @param key key
* @param value value
* @return
* @throws Exception
*/
public static boolean set(String key, String value) throws Exception {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
jedisPool.returnResource(jedis);
}
}
/**
* 向缓存中设置对象
*
* @param key
* @param value
* @return
*/
public static boolean set(String key, Object value) {
Jedis jedis = null;
try {
String objectJson = JSON.toJSONString(value);
jedis = jedisPool.getResource();
jedis.set(key, objectJson);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
jedisPool.returnResource(jedis);
}
}
/**
* 删除缓存中得对象,根据key
*
* @param key
* @return
*/
public static boolean del(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.del(key);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
jedisPool.returnResource(jedis);
}
}
/**
* 根据key 获取内容
*
* @param key
* @return
*/
public static Object get(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Object value = jedis.get(key);
return value;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
jedisPool.returnResource(jedis);
}
}
/**
* 根据key 获取对象
*
* @param key
* @return
*/
public static <T> T get(String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String value = jedis.get(key);
return JSON.parseObject(value, clazz);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
jedisPool.returnResource(jedis);
}
}
}
\ No newline at end of file
package com.geekq.admin.service.impl; package com.geekq.admin.service.impl;
import com.geekq.admin.entity.Account;
import com.geekq.admin.entity.IpLog; import com.geekq.admin.entity.IpLog;
import com.geekq.admin.entity.Logininfo; import com.geekq.admin.entity.Logininfo;
import com.geekq.admin.entity.Userinfo; import com.geekq.admin.entity.Userinfo;
import com.geekq.admin.mapper.AccountMapper;
import com.geekq.admin.mapper.IpLogMapper; import com.geekq.admin.mapper.IpLogMapper;
import com.geekq.admin.mapper.LogininfoMapper; import com.geekq.admin.mapper.LogininfoMapper;
import com.geekq.admin.mapper.UserinfoMapper; import com.geekq.admin.mapper.UserinfoMapper;
import com.geekq.admin.service.ILogininfoService; import com.geekq.admin.service.ILogininfoService;
import com.geekq.admin.service.RedisCacheStorageService;
import com.geekq.admin.utils.UserContext; import com.geekq.admin.utils.UserContext;
import com.geekq.common.enums.Constants; import com.geekq.common.enums.Constants;
import com.geekq.common.enums.ResultStatus; import com.geekq.common.enums.ResultStatus;
...@@ -37,6 +40,11 @@ public class LogininfoServiceImpl implements ILogininfoService { ...@@ -37,6 +40,11 @@ public class LogininfoServiceImpl implements ILogininfoService {
@Autowired @Autowired
private UserinfoMapper userinfoMapper; private UserinfoMapper userinfoMapper;
@Autowired
private AccountMapper accountMapper;
@Autowired
private RedisCacheStorageService redisService;
@Override @Override
public void register(String username, String password) { public void register(String username, String password) {
...@@ -54,7 +62,13 @@ public class LogininfoServiceImpl implements ILogininfoService { ...@@ -54,7 +62,13 @@ public class LogininfoServiceImpl implements ILogininfoService {
logininfo.setLastLoginDate(new Date()); logininfo.setLastLoginDate(new Date());
logininfo.setSalt(salt); logininfo.setSalt(salt);
this.loginInfoMapper.insert(logininfo); this.loginInfoMapper.insert(logininfo);
//初始化一个Userinfo
//初始化一个account
Account account = Account.empty(logininfo.getId());
accountMapper.insert(account);
//初始化一个Userinfo
Userinfo userinfo = Userinfo.empty(logininfo.getId()); Userinfo userinfo = Userinfo.empty(logininfo.getId());
int result = this.userinfoMapper.insert(userinfo); int result = this.userinfoMapper.insert(userinfo);
}else{ }else{
...@@ -78,7 +92,8 @@ public class LogininfoServiceImpl implements ILogininfoService { ...@@ -78,7 +92,8 @@ public class LogininfoServiceImpl implements ILogininfoService {
Logininfo current = this.loginInfoMapper.login(name, Logininfo current = this.loginInfoMapper.login(name,
MD5Utils.formPassToDBPass(password,salt), userType); MD5Utils.formPassToDBPass(password,salt), userType);
if(current != null){ if(current != null){
UserContext.putLogininfo(current); redisService.set("Login"+current.getNickname(),current);
// RedisCacheStorageService.set("login"+current.getId().toString(),10000,current);
log.setLoginInfoId(current.getId()); log.setLoginInfoId(current.getId());
log.setLoginState(IpLog.LOGINSTATE_SUCCESS); log.setLoginState(IpLog.LOGINSTATE_SUCCESS);
} }
......
package com.geekq.admin.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.io.Serializable;
@Service
public class RedisCache implements Serializable {
/**
* 日志记录
*/
final static Logger LOG = LoggerFactory.getLogger(RedisCache.class);
/**
* redis 连接池
*/
@Autowired
private JedisPool pool;
/*static {
if (pool == null) {
//读取相关的配置
ResourceBundle resourceBundle = ResourceBundle.getBundle("redis");
int maxActive = Integer.parseInt(resourceBundle.getString("redis.maxActive"));
int maxIdle = Integer.parseInt(resourceBundle.getString("redis.maxIdle"));
int maxWait = Integer.parseInt(resourceBundle.getString("redis.maxWait"));
String host = resourceBundle.getString("redis.host");
int port = Integer.parseInt(resourceBundle.getString("redis.port"));
String pass = resourceBundle.getString("redis.pass");
JedisPoolConfig config = new JedisPoolConfig();
//设置最大连接数
config.setMaxTotal(maxActive);
//设置最大空闲数
config.setMaxIdle(maxIdle);
//设置超时时间
config.setMaxWaitMillis(maxWait);
//初始化连接池
pool = new JedisPool(config, host, port, 2000, pass);
}
}*/
/**
* 获取jedis
*
* @return jedis
*/
public Jedis getResource() {
Jedis jedis = null;
try {
jedis = pool.getResource();
} catch (Exception e) {
LOG.info("can't get the redis resource");
}
return jedis;
}
/**
* 关闭连接
*
* @param jedis j
*/
public void disconnect(Jedis jedis) {
jedis.disconnect();
}
/**
* 将jedis 返还连接池
*
* @param jedis j
*/
public void returnResource(Jedis jedis) {
if (null != jedis) {
try {
pool.returnResource(jedis);
} catch (Exception e) {
LOG.info("can't return jedis to jedisPool");
}
}
}
/**
* 无法返还jedispool,释放jedis客户端对象
*
* @param jedis j
*/
public void brokenResource(Jedis jedis) {
if (jedis != null) {
try {
pool.returnBrokenResource(jedis);
} catch (Exception e) {
LOG.info("can't release jedis Object");
}
}
}
}
package com.geekq.admin.service.impl;
import com.alibaba.fastjson.JSON;
import com.geekq.admin.entity.Logininfo;
import com.geekq.admin.service.RedisCacheStorageService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
@Service("redisCacheStorageServiceImpl")
public class RedisCacheStorageServiceImpl implements RedisCacheStorageService {
final static Logger LOG = LoggerFactory.getLogger(RedisCache.class);
@Autowired
private RedisCache redisCache;
@Override
public boolean set(String key, Object value) {
Jedis jedis = null;
// 将key 和value 转换成 json 对象
// String jKey = JSON.toJSONString(key);
String jValue = JSON.toJSONString(value);
// 操作是否成功
boolean isSucess = true;
if (StringUtils.isEmpty(key)) {
LOG.info("key is empty");
return false;
}
try {
// 获取客户端对象
jedis = redisCache.getResource();
// 执行插入
jedis.set(key,jValue);
} catch (Exception e) {
LOG.info("client can't connect server");
isSucess = false;
if (null != jedis) {
// 释放jedis对象
redisCache.brokenResource(jedis);
}
return false;
} finally {
if (isSucess) {
// 返还连接池
redisCache.returnResource(jedis);
}
}
return true;
}
@Override
public Logininfo get(String key) {
Jedis jedis = null;
try {
jedis = redisCache.getResource();
//生成真正的key
String str = jedis.get(key);
Logininfo t = stringToBean(str, Logininfo.class);
return t;
}finally {
redisCache.returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public static <T> T stringToBean(String str, Class<T> clazz) {
if(str == null || str.length() <= 0 || clazz == null) {
return null;
}
if(clazz == int.class || clazz == Integer.class) {
return (T)Integer.valueOf(str);
}else if(clazz == String.class) {
return (T)str;
}else if(clazz == long.class || clazz == Long.class) {
return (T)Long.valueOf(str);
}else {
return JSON.toJavaObject(JSON.parseObject(str), clazz);
}
}
}
package com.geekq.admin.service.impl;
import com.geekq.admin.entity.Userinfo;
import com.geekq.admin.mapper.UserinfoMapper;
import com.geekq.admin.service.IUserService;
import com.geekq.admin.utils.UserContext;
import com.geekq.common.utils.numcal.BitStatesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service("userServiceImpl")
public class UserServiceImpl implements IUserService {
@Autowired
private UserinfoMapper userinfoMapper;
/*@Autowired
private ISendVerifyCodeService verifyCodeService;*/
/*
@Value("${db.timeout}")
private String salt;
*/
@Override
public void update(Userinfo userinfo) {
/* int ret = userinfoMapper.updateByPrimaryKey(userinfo,salt);
if (ret <= 0) {
throw new RuntimeException("乐观锁失败");*/
/* throw new RuntimeException("Userinfo对象:" + userinfo.getId()
+ " 乐观锁失败!");*/
}
@Override
public Userinfo get(Long id) {
return null;/*userinfoMapper.selectByPrimaryKey(id,salt);*/
}
@Override
public boolean bindPhone(String phoneNumber, String verifyCode) {
return false;
}
/*@Override
public boolean bindPhone(String phoneNumber, String verifyCode) {
boolean ret = verifyCodeService.verifyCode(phoneNumber, verifyCode);
if (ret) {
Userinfo ui = this.get(UserContext.getCurrent().getId());
ui.setPhoneNumber(phoneNumber);
ui.addState(BitStatesUtils.OP_BIND_PHONE);
this.update(ui);
return true;
}
return false;
}*/
@Override
public void updateBasicInfo(Userinfo userinfo) {
/* Userinfo current = this.userinfoMapper.selectByPrimaryKey(UserContext
.getCurrent().getId(),salt);*/
/* current.setEducationBackground(userinfo.getEducationBackground());
current.setHouseCondition(userinfo.getHouseCondition());
current.setIncomeGrade(userinfo.getIncomeGrade());
current.setKidCount(userinfo.getKidCount());
current.setMarriage(userinfo.getMarriage());
if (!current.getBaseInfo()) {
current.addState(BitStatesUtils.OP_BASE_INFO);
}
this.update(current);*/
}
}
...@@ -2,23 +2,59 @@ package com.geekq.admin.utils; ...@@ -2,23 +2,59 @@ package com.geekq.admin.utils;
import com.geekq.admin.entity.Logininfo; import com.geekq.admin.entity.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class UserContext { public class UserContext {
public static final String LOGIN_IN_SESSION = "logininfo"; @Autowired
public static final String VERIFYCODE_IN_SESSION = "VERIFYCODE_IN_SESSION"; private HttpSession session;
private static HttpServletRequest getRequest() { @Autowired
return ((ServletRequestAttributes) RequestContextHolder private HttpServletRequest request;
.getRequestAttributes()).getRequest();
} public static final String LOGIN_IN_SESSION = "logininfo";
public static final String VERIFYCODE_IN_SESSION = "VERIFYCODE_IN_SESSION";
@Bean
public RequestContextListener requestContextListener(){
return new RequestContextListener();
}
/* @Autowired
private RedisService redisService;*/
private static HttpServletRequest getRequest() {
return ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
}
private static ThreadLocal<Logininfo> userHolder = new ThreadLocal<Logininfo>();
/* public static void putLogininfo(Logininfo user) {
userHolder.set(user);
}
public static Logininfo getCurrent() {
return userHolder.get();
}*/
public static void removeUser() {
userHolder.remove();
}
public static void putLogininfo(Logininfo logininfo) { public static void putLogininfo(Logininfo logininfo) {
getRequest().getSession().setAttribute(LOGIN_IN_SESSION, logininfo); HttpServletRequest a = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
HttpSession b = a.getSession();
b.setAttribute(LOGIN_IN_SESSION, logininfo);
} }
public static Logininfo getCurrent() { public static Logininfo getCurrent() {
......
jdbc.driver=com.mysql.jdbc.Driver jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/miaosha2?characterEncoding=utf-8 jdbc.url=jdbc:mysql://localhost:3306/miaosha2?characterEncoding=utf-8
jdbc.username=root jdbc.username=root
jdbc.password=nihaoma jdbc.password=aixiyue11
db.properties
\ No newline at end of file
#访问地址
redis.host=39.107.245.253
redis.port=6379
redis.pass=youxin11
redis.maxIdle=25
redis.maxActive=100
redis.maxWait=1000
redis.testOnBorrow=false
redis.testOnReturn=false
...@@ -52,4 +52,5 @@ ...@@ -52,4 +52,5 @@
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.geekq.admin.mapper"></property> <property name="basePackage" value="com.geekq.admin.mapper"></property>
</bean> </bean>
</beans> </beans>
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
<dubbo:application name="miaosha-service"></dubbo:application> <dubbo:application name="miaosha-service"></dubbo:application>
<!-- 注册中心的配置,使用zk暴露服务 --> <!-- 注册中心的配置,使用zk暴露服务 -->
<dubbo:registry protocol="zookeeper" address="localhost:2181"></dubbo:registry> <dubbo:registry protocol="zookeeper" address="39.107.245.253:2181"></dubbo:registry>
<!-- 定义暴露服务的端口号 --> <!-- 定义暴露服务的端口号 -->
<dubbo:protocol name="dubbo" port="20881" ></dubbo:protocol> <dubbo:protocol name="dubbo" port="20881" ></dubbo:protocol>
...@@ -21,4 +21,10 @@ ...@@ -21,4 +21,10 @@
<dubbo:service retries="3" interface="com.geekq.admin.service.ILogininfoService" <dubbo:service retries="3" interface="com.geekq.admin.service.ILogininfoService"
ref="logininfoServiceImpl" timeout="60000"></dubbo:service> ref="logininfoServiceImpl" timeout="60000"></dubbo:service>
<dubbo:service retries="3" interface="com.geekq.admin.service.IUserService"
ref="userServiceImpl" timeout="60000"></dubbo:service>
<dubbo:service timeout="60000" retries="3"
interface="com.geekq.admin.service.RedisCacheStorageService" ref="redisCacheStorageServiceImpl" />
</beans> </beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- 加载redis参数 -->
<context:property-placeholder location="classpath:resource/redis.properties" />
<!-- 自动注解 -->
<!--<context:component-scan base-package="service.impl" />-->
<!-- jedis 连接池配置参数: -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 设置最大连接数 -->
<property name="maxTotal" value="${redis.maxActive}"></property>
<!-- 设置最大空闲数 -->
<property name="maxIdle" value="${redis.maxIdle}"></property>
<!-- 设置超时时间 -->
<property name="maxWaitMillis" value="${redis.maxWait}"></property>
<property name="testOnBorrow" value="${redis.testOnBorrow}"></property>
<property name="testOnReturn" value="${redis.testOnReturn}"></property>
</bean>
<!-- jedis 连接池 连接本地redis服务 构造器注入 -->
<bean id="pool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="poolConfig"/>
<constructor-arg index="1" value="${redis.host}"/>
<constructor-arg index="2" value="${redis.port}"/>
<constructor-arg index="3" value="${redis.maxWait}"/>
<constructor-arg index="4" value="${redis.pass}"/>
</bean>
<!-- redis cache config -->
<!-- <bean id="redisCache" class="client.RedisCache">
<property name="pool" ref="pool"/>
</bean>-->
</beans>
\ No newline at end of file
...@@ -2,10 +2,14 @@ ...@@ -2,10 +2,14 @@
<beans xmlns="http://www.springframework.org/schema/beans" <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<import resource="classpath:spring/applicationContext-dao.xml"/> <import resource="classpath:spring/applicationContext-dao.xml"/>
<import resource="classpath:spring/applicationContext-dubbo-provider.xml"/> <import resource="classpath:spring/applicationContext-dubbo-provider.xml"/>
<import resource="classpath:spring/applicationContext-service.xml"/> <import resource="classpath:spring/applicationContext-service.xml"/>
<import resource="classpath:spring/applicationContext-transaction.xml"/> <import resource="classpath:spring/applicationContext-transaction.xml"/>
<import resource="classpath:spring/applicationContext-redis.xml"/>
</beans> </beans>
...@@ -14,5 +14,9 @@ ...@@ -14,5 +14,9 @@
<listener> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> </listener>
<!-- 必须配置这个listener,才能在spring中使用RequestContextHolder -->
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
</web-app> </web-app>
...@@ -21,6 +21,12 @@ ...@@ -21,6 +21,12 @@
<artifactId>miaosha-admin-api</artifactId> <artifactId>miaosha-admin-api</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency>
<groupId>com.geekq</groupId>
<artifactId>miaosha-admin-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!-- freemarker --> <!-- freemarker -->
<dependency> <dependency>
<groupId>org.freemarker</groupId> <groupId>org.freemarker</groupId>
......
...@@ -2,12 +2,14 @@ package com.geekq.web.controller; ...@@ -2,12 +2,14 @@ package com.geekq.web.controller;
import com.geekq.admin.entity.Logininfo; import com.geekq.admin.entity.Logininfo;
import com.geekq.admin.service.ILogininfoService; import com.geekq.admin.service.ILogininfoService;
import com.geekq.admin.service.RedisCacheStorageService;
import com.geekq.common.enums.Constants; import com.geekq.common.enums.Constants;
import com.geekq.common.utils.resultbean.ResultGeekQ; import com.geekq.common.utils.resultbean.ResultGeekQ;
import com.geekq.common.vo.LoginVo; import com.geekq.common.vo.LoginVo;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
...@@ -28,15 +30,24 @@ public class LoginController extends BaseController { ...@@ -28,15 +30,24 @@ public class LoginController extends BaseController {
@Autowired @Autowired
private ILogininfoService iLogininfoService; private ILogininfoService iLogininfoService;
@Autowired
private RedisCacheStorageService redisCacheStorageService;
@RequestMapping("/login" ) @RequestMapping("/login" )
@ResponseBody @ResponseBody
public ResultGeekQ<Boolean> dologin(HttpServletResponse response, public ResultGeekQ<Logininfo> dologin(HttpServletResponse response,
HttpServletRequest request, HttpServletRequest request,
String username, String password) { String username, String password) {
ResultGeekQ<Boolean> result = ResultGeekQ.build(); ResultGeekQ<Logininfo> result = ResultGeekQ.build();
ResultGeekQ<Logininfo> login = this.iLogininfoService.login(username, password, ResultGeekQ<Logininfo> login = this.iLogininfoService.login(username, password,
Constants.USERTYPE_NORMAL,request.getRemoteAddr()); Constants.USERTYPE_NORMAL,request.getRemoteAddr());
if(ResultGeekQ.isSuccess(login)){ result.setData(login.getData());
if(!ResultGeekQ.isSuccess(login)){
result.withError(login.getCode(),login.getMessage()); result.withError(login.getCode(),login.getMessage());
} }
return result; return result;
......
package com.geekq.web.controller;
import com.geekq.admin.entity.Logininfo;
import com.geekq.admin.service.IAccountService;
import com.geekq.admin.service.IUserService;
import com.geekq.admin.service.RedisCacheStorageService;
import com.geekq.admin.utils.UserContext;
import com.geekq.web.interceptor.RequiredLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class PersonController extends BaseController {
@Autowired
private IUserService userinfoService;
@Autowired
private IAccountService accountService;
@Autowired
private RedisCacheStorageService redisService;
@RequiredLogin
@RequestMapping("/personal")
public String personal(Model model) {
//从中拿到 用户信息对象
Logininfo info = redisService.get("Loginqiurunze11");
model.addAttribute("userinfo", userinfoService.get(info.getId()));
// model.addAttribute("account", accountService.get(info.getId()));
return "personal";
}
}
package com.geekq.web.interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AddGlobalUtilInterceptor extends HandlerInterceptorAdapter {
/* @Autowired
private SystemDictionaryUtil systemDicUtil;*/
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
/*
modelAndView.addObject("_DicUtil", systemDicUtil);
*/
}
super.postHandle(request, response, handler, modelAndView);
}
}
package com.geekq.web.interceptor; package com.geekq.web.interceptor;
import com.geekq.web.utils.UserContext; import com.geekq.admin.entity.Logininfo;
import com.geekq.admin.service.RedisCacheStorageService;
import com.geekq.admin.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor extends HandlerInterceptorAdapter { public class LoginInterceptor extends HandlerInterceptorAdapter {
@Autowired
private RedisCacheStorageService redisService;
@Override @Override
public boolean preHandle(HttpServletRequest request, public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception { HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) { if (handler instanceof HandlerMethod) {
HandlerMethod hm = (HandlerMethod) handler; HandlerMethod hm = (HandlerMethod) handler;
RequiredLogin rl = hm.getMethodAnnotation(RequiredLogin.class); RequiredLogin rl = hm.getMethodAnnotation(RequiredLogin.class);
if (rl != null) { System.out.println(request.getParameter("username"));
if (request.getSession().getAttribute( String username =request.getParameter("username");
UserContext.LOGIN_IN_SESSION) == null) { if (rl != null) {
Logininfo current = redisService.get("Login"+username);
if (current == null) {
response.sendRedirect("/login.html"); response.sendRedirect("/login.html");
return false; return false;
} }
......
package com.geekq.web.utils;
import com.geekq.admin.entity.Logininfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
public class UserContext {
public static final String LOGIN_IN_SESSION = "logininfo";
public static final String VERIFYCODE_IN_SESSION = "VERIFYCODE_IN_SESSION";
private static HttpServletRequest getRequest() {
return ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
}
public static void putLogininfo(Logininfo logininfo) {
getRequest().getSession().setAttribute(LOGIN_IN_SESSION, logininfo);
}
public static Logininfo getCurrent() {
return (Logininfo) getRequest().getSession().getAttribute(
LOGIN_IN_SESSION);
}
// public static void putVerifyCode(VerifyCode code) {
// getRequest().getSession().setAttribute(VERIFYCODE_IN_SESSION, code);
// }
//
// public static VerifyCode getVerifyCode() {
// return (VerifyCode) getRequest().getSession().getAttribute(
// VERIFYCODE_IN_SESSION);
// }
}
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
<dubbo:application name="miaosha-dubbo-web"></dubbo:application> <dubbo:application name="miaosha-dubbo-web"></dubbo:application>
<!-- 注册中心的配置,用于消费者的监听 --> <!-- 注册中心的配置,用于消费者的监听 -->
<dubbo:registry protocol="zookeeper" address="localhost:2181"></dubbo:registry> <dubbo:registry protocol="zookeeper" address="39.107.245.253:2181"></dubbo:registry>
<!--&lt;!&ndash; 监听服务,通过注册中心去进行查找,查找到后进行服务调用 &ndash;&gt;--> <!--&lt;!&ndash; 监听服务,通过注册中心去进行查找,查找到后进行服务调用 &ndash;&gt;-->
<!--<dubbo:reference id="itemService" interface="com.imooc.item.service.ItemsService"--> <!--<dubbo:reference id="itemService" interface="com.imooc.item.service.ItemsService"-->
...@@ -19,4 +19,13 @@ ...@@ -19,4 +19,13 @@
<dubbo:reference id="iLogininfoService" interface="com.geekq.admin.service.ILogininfoService" <dubbo:reference id="iLogininfoService" interface="com.geekq.admin.service.ILogininfoService"
retries="3" check="false" init="true"></dubbo:reference> retries="3" check="false" init="true"></dubbo:reference>
<dubbo:reference id="iUserService" interface="com.geekq.admin.service.IUserService"
retries="3" check="false" init="true"></dubbo:reference>
<dubbo:reference id="iAccountService" interface="com.geekq.admin.service.IAccountService"
retries="3" check="false" init="true"></dubbo:reference>
<dubbo:reference id="redisCacheStorageService" interface="com.geekq.admin.service.RedisCacheStorageService"
retries="3" check="false" init="true"></dubbo:reference>
</beans> </beans>
...@@ -42,12 +42,13 @@ ...@@ -42,12 +42,13 @@
//验证成功后,提交操作; //验证成功后,提交操作;
submitHandler:function(form){ submitHandler:function(form){
$(form).ajaxSubmit(function(data){ $(form).ajaxSubmit(function(data){
if(data.status='success'){ if(data.status == "SUCCESS"){
var username = data.data.nickname;
$.messager.confirm("提示","登陆成功,点击确定跳转到个人中心",function(){ $.messager.confirm("提示","登陆成功,点击确定跳转到个人中心",function(){
window.location.href="/personal.do"; window.location.href="/personal.do?username="+username;
}); });
}else{ }else{
$.messager.alert("提示",data.msg); $.messager.alert("提示","登录失败!");
} }
}); });
}, },
......
...@@ -85,7 +85,7 @@ ...@@ -85,7 +85,7 @@
}, },
submitHandler:function(form){ submitHandler:function(form){
$(form).ajaxSubmit(function(data){ $(form).ajaxSubmit(function(data){
if(data.data){ if(data.success){
$.messager.confirm("提示","注册成功,请重新登录系统!",function(){ $.messager.confirm("提示","注册成功,请重新登录系统!",function(){
window.location.href="/login.html"; window.location.href="/login.html";
}); });
......
...@@ -61,5 +61,4 @@ public class MD5Utils { ...@@ -61,5 +61,4 @@ public class MD5Utils {
return MD5(str); return MD5(str);
} }
} }
...@@ -37,6 +37,7 @@ public class AbstractResult { ...@@ -37,6 +37,7 @@ public class AbstractResult {
} }
public AbstractResult withError(int code, String message) { public AbstractResult withError(int code, String message) {
this.status = ResultStatus.SYSTEM_ERROR;
this.code = code; this.code = code;
this.message = message; this.message = message;
return this; return this;
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
<dubbo:application name="dubbo-consumer" /> <dubbo:application name="dubbo-consumer" />
<dubbo:registry protocol="zookeeper" address="localhost:2181"/> <dubbo:registry protocol="zookeeper" address="39.107.245.253:2181"/>
<dubbo:reference id="serviceAPI" timeout="50000" interface="com.geekq.dubbo.springboot.ServiceAPI" /> <dubbo:reference id="serviceAPI" timeout="50000" interface="com.geekq.dubbo.springboot.ServiceAPI" />
......
spring.application.name=dubbo-spring-boot-starter spring.application.name=dubbo-spring-boot-starter
spring.dubbo.server=true spring.dubbo.server=true
spring.dubbo.registry=zookeeper://localhost:2181 spring.dubbo.registry=zookeeper://39.107.245.253:2181
\ No newline at end of file \ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册