Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
Menu
Open sidebar
jinli gu
JeeSpringCloudV3.0
Commits
d5ba54ba
Commit
d5ba54ba
authored
Nov 12, 2018
by
Huang
Browse files
no commit message
parent
da9d3b1b
Changes
399
Show whitespace changes
Inline
Side-by-side
Too many changes to show.
To preserve performance only
20 of 399+
files are displayed.
Plain diff
Email patch
JeeSpringCloud/src/main/java/com/jeespring/common/persistence/proxy/PaginationMapperMethod.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.persistence.proxy
;
import
org.apache.ibatis.annotations.Param
;
import
org.apache.ibatis.binding.BindingException
;
import
org.apache.ibatis.mapping.MappedStatement
;
import
org.apache.ibatis.mapping.SqlCommandType
;
import
org.apache.ibatis.session.Configuration
;
import
org.apache.ibatis.session.RowBounds
;
import
org.apache.ibatis.session.SqlSession
;
import
com.jeespring.common.persistence.Page
;
import
java.lang.reflect.Method
;
import
java.util.ArrayList
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Map
;
/**
* <p>
* 执行代理类,扩展Mybatis的方式来让其Mapper接口来支持.
* </p>
*
* @author poplar.yfyang
* @version 1.0 2012-05-13 上午10:09
* @since JDK 1.5
*/
public
class
PaginationMapperMethod
{
private
final
SqlSession
sqlSession
;
private
final
Configuration
config
;
private
SqlCommandType
type
;
private
String
commandName
;
private
String
commandCountName
;
private
final
Class
<?>
declaringInterface
;
private
final
Method
method
;
private
Integer
rowBoundsIndex
;
private
Integer
paginationIndex
;
private
final
List
<
String
>
paramNames
;
private
final
List
<
Integer
>
paramPositions
;
private
boolean
hasNamedParameters
;
public
PaginationMapperMethod
(
Class
<?>
declaringInterface
,
Method
method
,
SqlSession
sqlSession
)
{
paramNames
=
new
ArrayList
<
String
>();
paramPositions
=
new
ArrayList
<
Integer
>();
this
.
sqlSession
=
sqlSession
;
this
.
method
=
method
;
this
.
config
=
sqlSession
.
getConfiguration
();
this
.
declaringInterface
=
declaringInterface
;
this
.
hasNamedParameters
=
false
;
setupFields
();
setupMethodSignature
();
setupCommandType
();
validateStatement
();
}
/**
* 代理执行方法。
*
* @param args 参数信息
* @return 执行结果
*/
@SuppressWarnings
(
"unchecked"
)
public
Object
execute
(
Object
[]
args
)
{
final
Object
param
=
getParam
(
args
);
Page
<
Object
>
page
;
RowBounds
rowBounds
;
if
(
paginationIndex
!=
null
)
{
page
=
(
Page
<
Object
>)
args
[
paginationIndex
];
rowBounds
=
new
RowBounds
(
page
.
getFirstResult
(),
page
.
getMaxResults
());
}
else
if
(
rowBoundsIndex
!=
null
)
{
rowBounds
=
(
RowBounds
)
args
[
rowBoundsIndex
];
page
=
new
Page
<
Object
>();
}
else
{
throw
new
BindingException
(
"Invalid bound statement (not found rowBounds or pagination in paramenters)"
);
}
page
.
setCount
(
executeForCount
(
param
));
page
.
setList
(
executeForList
(
param
,
rowBounds
));
return
page
;
}
/**
* 执行总数的方法,调用方法执行计算总数,取得总结果
*
* @param param 参数信息
* @return 查询的总记录数
*/
private
long
executeForCount
(
Object
param
)
{
Number
result
=
(
Number
)
sqlSession
.
selectOne
(
commandCountName
,
param
);
return
result
.
longValue
();
}
/**
* 取得分页的执行结果,返回的是纪录信息
*
* @param param 参数
* @param rowBounds row
* @return 纪录列表
*/
private
List
<
Object
>
executeForList
(
Object
param
,
RowBounds
rowBounds
)
{
return
sqlSession
.
selectList
(
commandName
,
param
,
rowBounds
);
}
/**
* 取得当前执行的参数信息
*
* @param args 参数
* @return 参数信息
*/
private
Object
getParam
(
Object
[]
args
)
{
final
int
paramCount
=
paramPositions
.
size
();
if
(
args
==
null
||
paramCount
==
0
)
{
return
null
;
}
else
if
(!
hasNamedParameters
&&
paramCount
==
1
)
{
return
args
[
paramPositions
.
get
(
0
)];
}
else
{
Map
<
String
,
Object
>
param
=
new
HashMap
<
String
,
Object
>();
for
(
int
i
=
0
;
i
<
paramCount
;
i
++)
{
param
.
put
(
paramNames
.
get
(
i
),
args
[
paramPositions
.
get
(
i
)]);
}
return
param
;
}
}
private
void
setupMethodSignature
()
{
final
Class
<?>[]
argTypes
=
method
.
getParameterTypes
();
for
(
int
i
=
0
;
i
<
argTypes
.
length
;
i
++)
{
if
(
Page
.
class
.
isAssignableFrom
(
argTypes
[
i
]))
{
paginationIndex
=
i
;
}
else
if
(
RowBounds
.
class
.
isAssignableFrom
(
argTypes
[
i
]))
{
rowBoundsIndex
=
i
;
}
else
{
String
paramName
=
String
.
valueOf
(
paramPositions
.
size
());
paramName
=
getParamNameFromAnnotation
(
i
,
paramName
);
paramNames
.
add
(
paramName
);
paramPositions
.
add
(
i
);
}
}
}
private
String
getParamNameFromAnnotation
(
int
i
,
String
paramName
)
{
Object
[]
annotations
=
method
.
getParameterAnnotations
()[
i
];
for
(
Object
annotation
:
annotations
)
{
if
(
annotation
instanceof
Param
)
{
hasNamedParameters
=
true
;
paramName
=
((
Param
)
annotation
).
value
();
}
}
return
paramName
;
}
/**
* 设置当前的查询总记录数的ID
*/
private
void
setupFields
()
{
commandName
=
declaringInterface
.
getName
()
+
"."
+
method
.
getName
();
commandCountName
=
commandName
+
"Count"
;
// 命名约定
}
/**
* 设置当前的参数的类型信息
*/
private
void
setupCommandType
()
{
MappedStatement
ms
=
config
.
getMappedStatement
(
commandName
);
type
=
ms
.
getSqlCommandType
();
if
(
type
!=
SqlCommandType
.
SELECT
)
{
throw
new
BindingException
(
"Unsupport execution method for: "
+
commandName
);
}
}
/**
* 验证Statement
*/
private
void
validateStatement
()
{
if
(!
config
.
hasStatement
(
commandName
))
{
throw
new
BindingException
(
"Invalid bound statement (not found): "
+
commandName
);
}
if
(!
config
.
hasStatement
(
commandCountName
))
{
throw
new
BindingException
(
"Invalid bound statement (not found): "
+
commandCountName
);
}
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/persistence/proxy/PaginationMapperProxy.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.persistence.proxy
;
import
org.apache.ibatis.binding.BindingException
;
import
org.apache.ibatis.binding.MapperMethod
;
import
org.apache.ibatis.session.SqlSession
;
import
com.jeespring.common.persistence.Page
;
import
com.jeespring.common.utils.Reflections
;
import
java.lang.reflect.InvocationHandler
;
import
java.lang.reflect.Method
;
import
java.lang.reflect.Proxy
;
import
java.util.HashSet
;
import
java.util.Set
;
/**
* <p>
* .
* </p>
*
* @author poplar.yfyang
* @version 1.0 2012-05-13 上午10:07
* @since JDK 1.5
*/
public
class
PaginationMapperProxy
implements
InvocationHandler
{
private
static
final
Set
<
String
>
OBJECT_METHODS
=
new
HashSet
<
String
>()
{
private
static
final
long
serialVersionUID
=
-
1782950882770203583L
;
{
add
(
"toString"
);
add
(
"getClass"
);
add
(
"hashCode"
);
add
(
"equals"
);
add
(
"wait"
);
add
(
"notify"
);
add
(
"notifyAll"
);
}
};
private
boolean
isObjectMethod
(
Method
method
)
{
return
OBJECT_METHODS
.
contains
(
method
.
getName
());
}
private
final
SqlSession
sqlSession
;
private
PaginationMapperProxy
(
final
SqlSession
sqlSession
)
{
this
.
sqlSession
=
sqlSession
;
}
@Override
public
Object
invoke
(
Object
proxy
,
Method
method
,
Object
[]
args
)
throws
Throwable
{
if
(
isObjectMethod
(
method
))
{
return
null
;
}
final
Class
<?>
declaringInterface
=
findDeclaringInterface
(
proxy
,
method
);
if
(
Page
.
class
.
isAssignableFrom
(
method
.
getReturnType
()))
{
// 分页处理
return
new
PaginationMapperMethod
(
declaringInterface
,
method
,
sqlSession
).
execute
(
args
);
}
// 原处理方式
final
MapperMethod
mapperMethod
=
new
MapperMethod
(
declaringInterface
,
method
,
sqlSession
.
getConfiguration
());
final
Object
result
=
mapperMethod
.
execute
(
sqlSession
,
args
);
if
(
result
==
null
&&
method
.
getReturnType
().
isPrimitive
())
{
throw
new
BindingException
(
"Mapper method '"
+
method
.
getName
()
+
"' ("
+
method
.
getDeclaringClass
()
+
") attempted to return null from a method with a primitive return type ("
+
method
.
getReturnType
()
+
")."
);
}
return
result
;
}
private
Class
<?>
findDeclaringInterface
(
Object
proxy
,
Method
method
)
{
Class
<?>
declaringInterface
=
null
;
for
(
Class
<?>
mapperFaces
:
proxy
.
getClass
().
getInterfaces
())
{
Method
m
=
Reflections
.
getAccessibleMethod
(
mapperFaces
,
method
.
getName
(),
method
.
getParameterTypes
());
if
(
m
!=
null
)
{
declaringInterface
=
mapperFaces
;
}
}
if
(
declaringInterface
==
null
)
{
throw
new
BindingException
(
"Could not find interface with the given method "
+
method
);
}
return
declaringInterface
;
}
@SuppressWarnings
(
"unchecked"
)
public
static
<
T
>
T
newMapperProxy
(
Class
<
T
>
mapperInterface
,
SqlSession
sqlSession
)
{
ClassLoader
classLoader
=
mapperInterface
.
getClassLoader
();
Class
<?>[]
interfaces
=
new
Class
[]{
mapperInterface
};
PaginationMapperProxy
proxy
=
new
PaginationMapperProxy
(
sqlSession
);
return
(
T
)
Proxy
.
newProxyInstance
(
classLoader
,
interfaces
,
proxy
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/persistence/proxy/PaginationMapperRegistry.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.persistence.proxy
;
import
org.apache.ibatis.binding.BindingException
;
import
org.apache.ibatis.binding.MapperRegistry
;
import
org.apache.ibatis.session.Configuration
;
import
org.apache.ibatis.session.SqlSession
;
/**
* <p>
* .
* </p>
*
* @author poplar.yfyang
* @version 1.0 2012-05-13 上午10:06
* @since JDK 1.5
*/
public
class
PaginationMapperRegistry
extends
MapperRegistry
{
public
PaginationMapperRegistry
(
Configuration
config
)
{
super
(
config
);
}
@Override
public
<
T
>
T
getMapper
(
Class
<
T
>
type
,
SqlSession
sqlSession
)
{
if
(!
hasMapper
(
type
))
{
throw
new
BindingException
(
"Type "
+
type
+
" is not known to the MapperRegistry."
);
}
try
{
return
PaginationMapperProxy
.
newMapperProxy
(
type
,
sqlSession
);
}
catch
(
Exception
e
)
{
throw
new
BindingException
(
"Error getting mapper instance. Cause: "
+
e
,
e
);
}
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/redis/JedisUtils.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright © 2012-2016 <a href="https://www.jeespring.org>JeeSpring</a> All rights reserved.
*/
package
com.jeespring.common.redis
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.Set
;
import
com.jeespring.common.utils.ObjectUtils
;
import
com.jeespring.common.utils.SpringContextHolder
;
import
com.jeespring.common.utils.StringUtils
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
com.google.common.collect.Lists
;
import
com.google.common.collect.Maps
;
import
com.google.common.collect.Sets
;
import
redis.clients.jedis.Jedis
;
import
redis.clients.jedis.JedisPool
;
import
redis.clients.jedis.exceptions.JedisException
;
/**
* Jedis Cache 工具类
*
* @author JeeSpring
* @version 2014-6-29
*/
public
class
JedisUtils
{
private
static
Logger
logger
=
LoggerFactory
.
getLogger
(
JedisUtils
.
class
);
private
static
JedisPool
jedisPool
=
SpringContextHolder
.
getBean
(
JedisPool
.
class
);
//public static final String KEY_PREFIX = Global.getConfig("redis.keyPrefix");
/**
* 获取缓存
* @param key 键
* @return 值
*/
public
static
String
get
(
String
key
)
{
String
value
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
key
))
{
value
=
jedis
.
get
(
key
);
value
=
StringUtils
.
isNotBlank
(
value
)
&&
!
"nil"
.
equalsIgnoreCase
(
value
)
?
value
:
null
;
logger
.
debug
(
"get {} = {}"
,
key
,
value
);
}
}
catch
(
Exception
e
)
{
logger
.
warn
(
"get {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
value
;
}
/**
* 获取缓存
* @param key 键
* @return 值
*/
public
static
Object
getObject
(
String
key
)
{
Object
value
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
value
=
toObject
(
jedis
.
get
(
getBytesKey
(
key
)));
logger
.
debug
(
"getObject {} = {}"
,
key
,
value
);
}
}
catch
(
Exception
e
)
{
logger
.
warn
(
"getObject {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
value
;
}
/**
* 设置缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public
static
String
set
(
String
key
,
String
value
,
int
cacheSeconds
)
{
String
result
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
result
=
jedis
.
set
(
key
,
value
);
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
}
logger
.
debug
(
"set {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"set {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 设置缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public
static
String
setObject
(
String
key
,
Object
value
,
int
cacheSeconds
)
{
String
result
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
result
=
jedis
.
set
(
getBytesKey
(
key
),
toBytes
(
value
));
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
}
logger
.
debug
(
"setObject {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"setObject {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 获取List缓存
* @param key 键
* @return 值
*/
public
static
List
<
String
>
getList
(
String
key
)
{
List
<
String
>
value
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
key
))
{
value
=
jedis
.
lrange
(
key
,
0
,
-
1
);
logger
.
debug
(
"getList {} = {}"
,
key
,
value
);
}
}
catch
(
Exception
e
)
{
logger
.
warn
(
"getList {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
value
;
}
/**
* 获取List缓存
* @param key 键
* @return 值
*/
public
static
List
<
Object
>
getObjectList
(
String
key
)
{
List
<
Object
>
value
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
List
<
byte
[]>
list
=
jedis
.
lrange
(
getBytesKey
(
key
),
0
,
-
1
);
value
=
Lists
.
newArrayList
();
for
(
byte
[]
bs
:
list
){
value
.
add
(
toObject
(
bs
));
}
logger
.
debug
(
"getObjectList {} = {}"
,
key
,
value
);
}
}
catch
(
Exception
e
)
{
logger
.
warn
(
"getObjectList {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
value
;
}
/**
* 设置List缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public
static
long
setList
(
String
key
,
List
<
String
>
value
,
int
cacheSeconds
)
{
long
result
=
0
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
key
))
{
jedis
.
del
(
key
);
}
result
=
jedis
.
rpush
(
key
,
(
String
[])
value
.
toArray
());
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
}
logger
.
debug
(
"setList {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"setList {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 设置List缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public
static
long
setObjectList
(
String
key
,
List
<
Object
>
value
,
int
cacheSeconds
)
{
long
result
=
0
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
jedis
.
del
(
key
);
}
List
<
byte
[]>
list
=
Lists
.
newArrayList
();
for
(
Object
o
:
value
){
list
.
add
(
toBytes
(
o
));
}
result
=
jedis
.
rpush
(
getBytesKey
(
key
),
(
byte
[][])
list
.
toArray
());
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
}
logger
.
debug
(
"setObjectList {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"setObjectList {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 向List缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public
static
long
listAdd
(
String
key
,
String
...
value
)
{
long
result
=
0
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
result
=
jedis
.
rpush
(
key
,
value
);
logger
.
debug
(
"listAdd {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"listAdd {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 向List缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public
static
long
listObjectAdd
(
String
key
,
Object
...
value
)
{
long
result
=
0
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
List
<
byte
[]>
list
=
Lists
.
newArrayList
();
for
(
Object
o
:
value
){
list
.
add
(
toBytes
(
o
));
}
result
=
jedis
.
rpush
(
getBytesKey
(
key
),
(
byte
[][])
list
.
toArray
());
logger
.
debug
(
"listObjectAdd {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"listObjectAdd {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 获取缓存
* @param key 键
* @return 值
*/
public
static
Set
<
String
>
getSet
(
String
key
)
{
Set
<
String
>
value
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
key
))
{
value
=
jedis
.
smembers
(
key
);
logger
.
debug
(
"getSet {} = {}"
,
key
,
value
);
}
}
catch
(
Exception
e
)
{
logger
.
warn
(
"getSet {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
value
;
}
/**
* 获取缓存
* @param key 键
* @return 值
*/
public
static
Set
<
Object
>
getObjectSet
(
String
key
)
{
Set
<
Object
>
value
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
value
=
Sets
.
newHashSet
();
Set
<
byte
[]>
set
=
jedis
.
smembers
(
getBytesKey
(
key
));
for
(
byte
[]
bs
:
set
){
value
.
add
(
toObject
(
bs
));
}
logger
.
debug
(
"getObjectSet {} = {}"
,
key
,
value
);
}
}
catch
(
Exception
e
)
{
logger
.
warn
(
"getObjectSet {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
value
;
}
/**
* 设置Set缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public
static
long
setSet
(
String
key
,
Set
<
String
>
value
,
int
cacheSeconds
)
{
long
result
=
0
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
key
))
{
jedis
.
del
(
key
);
}
result
=
jedis
.
sadd
(
key
,
(
String
[])
value
.
toArray
());
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
}
logger
.
debug
(
"setSet {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"setSet {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 设置Set缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public
static
long
setObjectSet
(
String
key
,
Set
<
Object
>
value
,
int
cacheSeconds
)
{
long
result
=
0
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
jedis
.
del
(
key
);
}
Set
<
byte
[]>
set
=
Sets
.
newHashSet
();
for
(
Object
o
:
value
){
set
.
add
(
toBytes
(
o
));
}
result
=
jedis
.
sadd
(
getBytesKey
(
key
),
(
byte
[][])
set
.
toArray
());
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
}
logger
.
debug
(
"setObjectSet {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"setObjectSet {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 向Set缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public
static
long
setSetAdd
(
String
key
,
String
...
value
)
{
long
result
=
0
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
result
=
jedis
.
sadd
(
key
,
value
);
logger
.
debug
(
"setSetAdd {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"setSetAdd {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 向Set缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public
static
long
setSetObjectAdd
(
String
key
,
Object
...
value
)
{
long
result
=
0
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
Set
<
byte
[]>
set
=
Sets
.
newHashSet
();
for
(
Object
o
:
value
){
set
.
add
(
toBytes
(
o
));
}
result
=
jedis
.
rpush
(
getBytesKey
(
key
),
(
byte
[][])
set
.
toArray
());
logger
.
debug
(
"setSetObjectAdd {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"setSetObjectAdd {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 获取Map缓存
* @param key 键
* @return 值
*/
public
static
Map
<
String
,
String
>
getMap
(
String
key
)
{
Map
<
String
,
String
>
value
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
key
))
{
value
=
jedis
.
hgetAll
(
key
);
logger
.
debug
(
"getMap {} = {}"
,
key
,
value
);
}
}
catch
(
Exception
e
)
{
logger
.
warn
(
"getMap {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
value
;
}
/**
* 获取Map缓存
* @param key 键
* @return 值
*/
public
static
Map
<
String
,
Object
>
getObjectMap
(
String
key
)
{
Map
<
String
,
Object
>
value
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
value
=
Maps
.
newHashMap
();
Map
<
byte
[],
byte
[]>
map
=
jedis
.
hgetAll
(
getBytesKey
(
key
));
for
(
Map
.
Entry
<
byte
[],
byte
[]>
e
:
map
.
entrySet
()){
value
.
put
(
StringUtils
.
toString
(
e
.
getKey
()),
toObject
(
e
.
getValue
()));
}
logger
.
debug
(
"getObjectMap {} = {}"
,
key
,
value
);
}
}
catch
(
Exception
e
)
{
logger
.
warn
(
"getObjectMap {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
value
;
}
/**
* 设置Map缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public
static
String
setMap
(
String
key
,
Map
<
String
,
String
>
value
,
int
cacheSeconds
)
{
String
result
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
key
))
{
jedis
.
del
(
key
);
}
result
=
jedis
.
hmset
(
key
,
value
);
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
}
logger
.
debug
(
"setMap {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"setMap {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 设置Map缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public
static
String
setObjectMap
(
String
key
,
Map
<
String
,
Object
>
value
,
int
cacheSeconds
)
{
String
result
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
jedis
.
del
(
key
);
}
Map
<
byte
[],
byte
[]>
map
=
Maps
.
newHashMap
();
for
(
Map
.
Entry
<
String
,
Object
>
e
:
value
.
entrySet
()){
map
.
put
(
getBytesKey
(
e
.
getKey
()),
toBytes
(
e
.
getValue
()));
}
result
=
jedis
.
hmset
(
getBytesKey
(
key
),
(
Map
<
byte
[],
byte
[]>)
map
);
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
}
logger
.
debug
(
"setObjectMap {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"setObjectMap {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 向Map缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public
static
String
mapPut
(
String
key
,
Map
<
String
,
String
>
value
)
{
String
result
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
result
=
jedis
.
hmset
(
key
,
value
);
logger
.
debug
(
"mapPut {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"mapPut {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 向Map缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public
static
String
mapObjectPut
(
String
key
,
Map
<
String
,
Object
>
value
)
{
String
result
=
null
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
Map
<
byte
[],
byte
[]>
map
=
Maps
.
newHashMap
();
for
(
Map
.
Entry
<
String
,
Object
>
e
:
value
.
entrySet
()){
map
.
put
(
getBytesKey
(
e
.
getKey
()),
toBytes
(
e
.
getValue
()));
}
result
=
jedis
.
hmset
(
getBytesKey
(
key
),
(
Map
<
byte
[],
byte
[]>)
map
);
logger
.
debug
(
"mapObjectPut {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"mapObjectPut {} = {}"
,
key
,
value
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 移除Map缓存中的值
* @param key 键
* @return
*/
public
static
long
mapRemove
(
String
key
,
String
mapKey
)
{
long
result
=
0
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
result
=
jedis
.
hdel
(
key
,
mapKey
);
logger
.
debug
(
"mapRemove {} {}"
,
key
,
mapKey
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"mapRemove {} {}"
,
key
,
mapKey
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 移除Map缓存中的值
* @param key 键
* @return
*/
public
static
long
mapObjectRemove
(
String
key
,
String
mapKey
)
{
long
result
=
0
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
result
=
jedis
.
hdel
(
getBytesKey
(
key
),
getBytesKey
(
mapKey
));
logger
.
debug
(
"mapObjectRemove {} {}"
,
key
,
mapKey
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"mapObjectRemove {} {}"
,
key
,
mapKey
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 判断Map缓存中的Key是否存在
* @param key 键
* @return
*/
public
static
boolean
mapExists
(
String
key
,
String
mapKey
)
{
boolean
result
=
false
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
result
=
jedis
.
hexists
(
key
,
mapKey
);
logger
.
debug
(
"mapExists {} {}"
,
key
,
mapKey
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"mapExists {} {}"
,
key
,
mapKey
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 判断Map缓存中的Key是否存在
* @param key 键
* @return
*/
public
static
boolean
mapObjectExists
(
String
key
,
String
mapKey
)
{
boolean
result
=
false
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
result
=
jedis
.
hexists
(
getBytesKey
(
key
),
getBytesKey
(
mapKey
));
logger
.
debug
(
"mapObjectExists {} {}"
,
key
,
mapKey
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"mapObjectExists {} {}"
,
key
,
mapKey
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 删除缓存
* @param key 键
* @return
*/
public
static
long
del
(
String
key
)
{
long
result
=
0
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
key
)){
result
=
jedis
.
del
(
key
);
logger
.
debug
(
"del {}"
,
key
);
}
else
{
logger
.
debug
(
"del {} not exists"
,
key
);
}
}
catch
(
Exception
e
)
{
logger
.
warn
(
"del {}"
,
key
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 删除缓存
* @param key 键
* @return
*/
public
static
long
delObject
(
String
key
)
{
long
result
=
0
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
if
(
jedis
.
exists
(
getBytesKey
(
key
))){
result
=
jedis
.
del
(
getBytesKey
(
key
));
logger
.
debug
(
"delObject {}"
,
key
);
}
else
{
logger
.
debug
(
"delObject {} not exists"
,
key
);
}
}
catch
(
Exception
e
)
{
logger
.
warn
(
"delObject {}"
,
key
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 缓存是否存在
* @param key 键
* @return
*/
public
static
boolean
exists
(
String
key
)
{
boolean
result
=
false
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
result
=
jedis
.
exists
(
key
);
logger
.
debug
(
"exists {}"
,
key
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"exists {}"
,
key
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 缓存是否存在
* @param key 键
* @return
*/
public
static
boolean
existsObject
(
String
key
)
{
boolean
result
=
false
;
Jedis
jedis
=
null
;
try
{
jedis
=
getResource
();
result
=
jedis
.
exists
(
getBytesKey
(
key
));
logger
.
debug
(
"existsObject {}"
,
key
);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"existsObject {}"
,
key
,
e
);
}
finally
{
returnResource
(
jedis
);
}
return
result
;
}
/**
* 获取资源
* @return
* @throws JedisException
*/
public
static
Jedis
getResource
()
throws
JedisException
{
Jedis
jedis
=
null
;
try
{
jedis
=
jedisPool
.
getResource
();
// logger.debug("getResource.", jedis);
}
catch
(
JedisException
e
)
{
logger
.
warn
(
"getResource."
,
e
);
returnBrokenResource
(
jedis
);
throw
e
;
}
return
jedis
;
}
/**
* 归还资源
* @param jedis
*/
public
static
void
returnBrokenResource
(
Jedis
jedis
)
{
if
(
jedis
!=
null
)
{
jedisPool
.
returnBrokenResource
(
jedis
);
}
}
/**
* 释放资源
* @param jedis
*/
public
static
void
returnResource
(
Jedis
jedis
)
{
if
(
jedis
!=
null
)
{
jedisPool
.
returnResource
(
jedis
);
}
}
/**
* 获取byte[]类型Key
* @return
*/
public
static
byte
[]
getBytesKey
(
Object
object
){
if
(
object
instanceof
String
){
return
StringUtils
.
getBytes
((
String
)
object
);
}
else
{
return
ObjectUtils
.
serialize
(
object
);
}
}
/**
* 获取byte[]类型Key
* @param key
* @return
*/
public
static
Object
getObjectKey
(
byte
[]
key
){
try
{
return
StringUtils
.
toString
(
key
);
}
catch
(
UnsupportedOperationException
uoe
){
try
{
return
JedisUtils
.
toObject
(
key
);
}
catch
(
UnsupportedOperationException
uoe2
){
uoe2
.
printStackTrace
();
}
}
return
null
;
}
/**
* Object转换byte[]类型
* @return
*/
public
static
byte
[]
toBytes
(
Object
object
){
return
ObjectUtils
.
serialize
(
object
);
}
/**
* byte[]型转换Object
* @return
*/
public
static
Object
toObject
(
byte
[]
bytes
){
return
ObjectUtils
.
unserialize
(
bytes
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/redis/RedisConfig.java
0 → 100644
View file @
d5ba54ba
package
com.jeespring.common.redis
;
import
org.springframework.boot.autoconfigure.EnableAutoConfiguration
;
import
org.springframework.boot.context.properties.ConfigurationProperties
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.data.redis.connection.jedis.JedisConnectionFactory
;
import
org.springframework.data.redis.core.RedisTemplate
;
import
org.springframework.data.redis.core.StringRedisTemplate
;
import
redis.clients.jedis.JedisPoolConfig
;
@Configuration
@EnableAutoConfiguration
public
class
RedisConfig
{
//private static Logger logger = Logger.getLogger(RedisConfig.class);
@Bean
@ConfigurationProperties
(
prefix
=
"spring.redis"
)
public
JedisPoolConfig
getRedisConfig
(){
JedisPoolConfig
config
=
new
JedisPoolConfig
();
return
config
;
}
@Bean
@ConfigurationProperties
(
prefix
=
"spring.redis"
)
public
JedisConnectionFactory
getConnectionFactory
(){
JedisConnectionFactory
factory
=
new
JedisConnectionFactory
();
JedisPoolConfig
config
=
getRedisConfig
();
factory
.
setPoolConfig
(
config
);
//logger.info("JedisConnectionFactory bean init success.");
return
factory
;
}
@Bean
public
RedisTemplate
<?,
?>
getRedisTemplate
(){
RedisTemplate
<?,?>
template
=
new
StringRedisTemplate
(
getConnectionFactory
());
return
template
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/redis/RedisRestController.java
0 → 100644
View file @
d5ba54ba
package
com.jeespring.common.redis
;
import
com.jeespring.common.web.Result
;
import
com.jeespring.common.web.ResultFactory
;
import
io.swagger.annotations.Api
;
import
io.swagger.annotations.ApiImplicitParam
;
import
io.swagger.annotations.ApiOperation
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.data.redis.core.ValueOperations
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RequestMethod
;
import
org.springframework.web.bind.annotation.RequestParam
;
import
org.springframework.web.bind.annotation.RestController
;
import
java.io.Serializable
;
import
java.util.Set
;
import
java.util.concurrent.TimeUnit
;
@RestController
@RequestMapping
(
"/rest/redis"
)
@Api
(
value
=
"Redis云数据缓存接口"
,
description
=
"Redis云数据缓存接口"
)
public
class
RedisRestController
{
@Autowired
private
RedisUtils
redisUtils
;
@RequestMapping
(
value
=
"/test"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis Test信息(Content-Type为text/html)"
,
notes
=
"Redis Test(Content-Type为text/html)"
)
public
String
test
(){
redisUtils
.
set
(
"Redis Test"
,
"Redis Test"
);
String
string
=
redisUtils
.
get
(
"Redis Test"
).
toString
();
return
string
;
}
/**
* 批量删除对应的value
*
* @param keys
*/
@RequestMapping
(
value
=
"/removeList"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis remove接口(Content-Type为text/html)"
,
notes
=
"Redis remove接口(Content-Type为text/html)"
)
public
Result
removeList
(
@RequestParam
(
required
=
false
)
String
keys
)
{
String
[]
keysList
=
keys
.
split
(
","
);
for
(
String
key:
keysList
)
{
redisUtils
.
remove
(
key
);
}
return
ResultFactory
.
getSuccessResult
(
"移除成功!"
);
}
/**
* 批量删除key
*
* @param pattern
*/
@RequestMapping
(
value
=
"/removePattern"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis remove pattern接口(Content-Type为text/html)"
,
notes
=
"Redis remove pattern接口接口(Content-Type为text/html)"
)
public
Result
removePattern
(
@RequestParam
(
required
=
false
)
String
pattern
)
{
redisUtils
.
removePattern
(
pattern
);
return
ResultFactory
.
getSuccessResult
(
"移除成功!"
);
}
@RequestMapping
(
value
=
"/removePatternShiroRedis"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis remove pattern Shiro Reids接口(Content-Type为text/html)"
,
notes
=
"Redis remove pattern Shiro Reids接口接口(Content-Type为text/html)"
)
public
Result
removePatternShiroReids
(
@RequestParam
(
required
=
false
)
String
pattern
)
{
redisUtils
.
removePatternShiroReids
(
pattern
);
return
ResultFactory
.
getSuccessResult
(
"移除成功!"
);
}
/**
* 删除对应的value
*
* @param key
*/
@RequestMapping
(
value
=
"/remove"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis remove接口(Content-Type为text/html)"
,
notes
=
"Redis remove接口(Content-Type为text/html)"
)
public
Result
remove
(
@RequestParam
(
required
=
false
)
String
key
)
{
redisUtils
.
remove
(
key
);
return
ResultFactory
.
getSuccessResult
(
"移除成功!"
);
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
@RequestMapping
(
value
=
"/exists"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis exists接口(Content-Type为text/html)"
,
notes
=
"Redis exists接口(Content-Type为text/html)"
)
public
Result
exists
(
@RequestParam
(
required
=
false
)
String
key
)
{
if
(
redisUtils
.
exists
(
key
))
{
return
ResultFactory
.
getSuccessResult
(
"存在!"
);
}
else
{
return
ResultFactory
.
getErrorResult
(
"不存在!"
);
}
}
/**
* 读取缓存
*
* @param key
* @return
*/
@RequestMapping
(
value
=
"/get"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis get接口(Content-Type为text/html)"
,
notes
=
"Redis get接口(Content-Type为text/html)"
)
public
Result
get
(
@RequestParam
(
required
=
false
)
String
key
)
{
if
(
redisUtils
.
exists
(
key
)){
Result
result
=
ResultFactory
.
getSuccessResult
();
Object
obj
=
redisUtils
.
get
(
key
);
if
(
obj
!=
null
)
{
result
.
setResultObject
(
obj
.
toString
());
}
return
result
;
}
else
{
return
ResultFactory
.
getErrorResult
(
"不存在!"
);
}
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@RequestMapping
(
value
=
"/set"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis set接口(Content-Type为text/html)"
,
notes
=
"Redis set接口(Content-Type为text/html)"
)
public
Result
set
(
@RequestParam
(
required
=
false
)
String
key
,
@RequestParam
(
required
=
false
)
String
value
)
{
if
(
redisUtils
.
set
(
key
,
value
)){
Result
result
=
ResultFactory
.
getSuccessResult
(
"添加/更新成功!"
);
return
result
;
}
else
{
return
ResultFactory
.
getErrorResult
(
"添加/更新失败!"
);
}
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@RequestMapping
(
value
=
"/setExpireTime"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis set expireTime接口(Content-Type为text/html)"
,
notes
=
"Redis set expireTime接口接口(Content-Type为text/html)"
)
public
Result
set
(
@RequestParam
(
required
=
false
)
String
key
,
@RequestParam
(
required
=
false
)
String
value
,
@RequestParam
(
required
=
false
)
Long
expireTime
)
{
if
(
redisUtils
.
set
(
key
,
value
,
expireTime
)){
Result
result
=
ResultFactory
.
getSuccessResult
(
"添加/更新成功!"
);
return
result
;
}
else
{
return
ResultFactory
.
getErrorResult
(
"添加/更新失败!"
);
}
}
/**
* 获取keys
*
* @param pattern
*/
@RequestMapping
(
value
=
"/getKyes"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis get kyes接口(Content-Type为text/html)"
,
notes
=
"Redis get kyes接口接口(Content-Type为text/html)"
)
public
Result
getKyes
(
@RequestParam
(
required
=
false
)
String
pattern
)
{
Set
<
String
>
keys
=
redisUtils
.
getKyes
(
pattern
);
Result
result
=
ResultFactory
.
getSuccessResult
(
"获取Keys成功!"
);
result
.
setResultObject
(
keys
);
return
result
;
}
@RequestMapping
(
value
=
"/getKyesAll"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis get kyes all接口(Content-Type为text/html)"
,
notes
=
"Redis get kyes all接口(Content-Type为text/html)"
)
public
Result
getKyesAll
()
{
Set
<
String
>
keys
=
redisUtils
.
getKyesAll
();
Result
result
=
ResultFactory
.
getSuccessResult
(
"获取Keys成功!"
);
result
.
setResultObject
(
keys
);
return
result
;
}
/**
* 获取keys
*
* @param pattern
*/
@RequestMapping
(
value
=
"/getCount"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis get count接口(Content-Type为text/html)"
,
notes
=
"Redis get count接口(Content-Type为text/html)"
)
public
Result
getCount
(
@RequestParam
(
required
=
false
)
String
pattern
)
{
Result
result
=
ResultFactory
.
getSuccessResult
(
"获取数量成功!"
);
result
.
setResultObject
(
redisUtils
.
getCount
());
return
result
;
}
@RequestMapping
(
value
=
"/getCountShiro"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis get count shiro接口(Content-Type为text/html)"
,
notes
=
"Redis get count shiro接口(Content-Type为text/html)"
)
public
Result
getCountShiro
(
@RequestParam
(
required
=
false
)
String
pattern
)
{
Result
result
=
ResultFactory
.
getSuccessResult
(
"获取数量成功!"
);
result
.
setResultObject
(
redisUtils
.
getCountShiro
());
return
result
;
}
/**
* 获取token的有效期(秒)
* @param key
*/
@RequestMapping
(
value
=
"/getExpireTime"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis get ExpireTime接口(Content-Type为text/html)"
,
notes
=
"Redis get ExpireTime接口接口(Content-Type为text/html)"
)
public
Result
getExpireTime
(
@RequestParam
(
required
=
false
)
String
key
){
Result
result
=
ResultFactory
.
getSuccessResult
(
"获取token的有效期(秒)成功!"
);
result
.
setResultObject
(
redisUtils
.
getExpireTime
(
key
));
return
result
;
}
/**
* 获取缓存有效期成功
*/
@RequestMapping
(
value
=
"/getExpire"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis get getExpire(Content-Type为text/html)"
,
notes
=
"Redis get getExpire(Content-Type为text/html)"
)
public
Result
getExpire
(){
Result
result
=
ResultFactory
.
getSuccessResult
(
"获取缓存有效期成功!"
);
result
.
setResultObject
(
RedisUtils
.
getExpire
());
return
result
;
}
/**
* 获取单点登录缓存有效期成功
*/
@RequestMapping
(
value
=
"/getExpireShiro"
,
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"Redis get getExpireShiro(Content-Type为text/html)"
,
notes
=
"Redis get getExpireShiro(Content-Type为text/html)"
)
public
Result
getExpireShiro
(){
Result
result
=
ResultFactory
.
getSuccessResult
(
"获取单点登录缓存有效期成功!"
);
result
.
setResultObject
(
RedisUtils
.
getExpireShiro
());
return
result
;
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/common/redis/RedisUtils.java
0 → 100644
View file @
d5ba54ba
package
com.jeespring.common.redis
;
import
java.io.Serializable
;
import
java.util.HashSet
;
import
java.util.Iterator
;
import
java.util.List
;
import
java.util.Set
;
import
java.util.concurrent.TimeUnit
;
import
com.jeespring.common.config.Global
;
import
com.jeespring.common.security.MD5Tools
;
import
com.sun.tools.javac.util.Convert
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.data.redis.core.RedisTemplate
;
import
org.springframework.data.redis.core.StringRedisTemplate
;
import
org.springframework.data.redis.core.ValueOperations
;
import
org.springframework.stereotype.Component
;
import
redis.clients.jedis.Jedis
;
/**
* redicache 工具类
* 在application.yml文件内的Spring-redis的run配置启动,true为启动;false为不启动;
*/
@SuppressWarnings
(
"unchecked"
)
@Component
public
class
RedisUtils
{
/**
* 日志对象
*/
private
static
Logger
logger
=
LoggerFactory
.
getLogger
(
RedisUtils
.
class
);
public
static
String
SHIRO_REDIS
=
"shiro_redis_cache"
;
public
static
String
SHIRO_REDIS_OBJECT
=
"org.apache.shiro.subject.SimplePrincipalCollection"
;
public
static
String
GET_ID
=
".get id="
;
public
static
String
TOTAL_KEY
=
".total key="
;
public
static
String
FIND_LIST_KEY
=
".findList key="
;
public
static
String
FIND_LIST_FIRST_KEY
=
".findListFirst key="
;
public
static
String
FIND_PAGE_KEY
=
".findPage key="
;
public
static
String
FIND_LIST_KEY_PATTERN
=
".findList key=*"
;
public
static
String
FIND_LIST_FIRST_KEY_PATTERN
=
".findListFirst key=*"
;
public
static
String
FIND_PAGE_KEY_PATTERN
=
".findPage key=*"
;
public
static
String
KEY_PREFIX
=
Global
.
getConfig
(
"spring.redis.keyPrefix"
);
public
static
Long
expireTime
=
Long
.
parseLong
(
Global
.
getConfig
(
"spring.redis.expireTime"
));
public
static
Long
expireTimeShiro
=
Long
.
parseLong
(
Global
.
getConfig
(
"spring.redis.expireTimeShiro"
));
public
static
String
RUN_MESSAGE
=
"请开启Redis服务,还有Redis密码配置是否有误,而且密码不能为空(为空时Redis服务会连接不上)。"
;
@SuppressWarnings
(
"rawtypes"
)
@Autowired
private
RedisTemplate
redisTemplate
;
@Autowired
private
StringRedisTemplate
stringRedisTemplate
;
public
static
String
getExpire
(){
if
(
expireTime
!=
null
)
{
return
String
.
valueOf
(
expireTime
/
60
)
+
"分钟"
;
}
else
{
return
"0分钟"
;
}
}
public
static
String
getExpireShiro
(){
if
(
expireTimeShiro
!=
null
)
{
return
String
.
valueOf
(
expireTimeShiro
/
60
)
+
"分钟"
;
}
else
{
return
"0分钟"
;
}
}
public
static
String
getKey
(
String
className
,
String
keyName
,
String
keyId
){
if
(
className
==
null
){
className
=
""
;}
if
(
keyId
==
null
){
keyId
=
""
;}
return
RedisUtils
.
KEY_PREFIX
+
className
+
keyName
+
keyId
;
}
public
static
String
getIdKey
(
String
className
,
String
keyId
){
if
(
className
==
null
){
className
=
""
;}
if
(
keyId
==
null
){
keyId
=
""
;}
return
RedisUtils
.
KEY_PREFIX
+
className
+
RedisUtils
.
GET_ID
+
keyId
;
}
public
static
String
getTotalKey
(
String
className
,
String
keyId
){
if
(
className
==
null
){
className
=
""
;}
if
(
keyId
==
null
){
keyId
=
""
;}
return
RedisUtils
.
KEY_PREFIX
+
className
+
RedisUtils
.
TOTAL_KEY
+
MD5Tools
.
MD5
(
keyId
).
substring
(
0
,
20
);
}
public
static
String
getFindListKey
(
String
className
,
String
keyId
){
if
(
className
==
null
){
className
=
""
;}
if
(
keyId
==
null
){
keyId
=
""
;}
return
RedisUtils
.
KEY_PREFIX
+
className
+
RedisUtils
.
FIND_LIST_KEY
+
MD5Tools
.
MD5
(
keyId
).
substring
(
0
,
20
);
}
public
static
String
getFindListFirstKey
(
String
className
,
String
keyId
){
if
(
className
==
null
){
className
=
""
;}
if
(
keyId
==
null
){
keyId
=
""
;}
return
RedisUtils
.
KEY_PREFIX
+
className
+
RedisUtils
.
FIND_LIST_FIRST_KEY
+
MD5Tools
.
MD5
(
keyId
).
substring
(
0
,
20
);
}
public
static
String
getFindPageKey
(
String
className
,
String
keyId
){
if
(
className
==
null
){
className
=
""
;}
if
(
keyId
==
null
){
keyId
=
""
;}
return
RedisUtils
.
KEY_PREFIX
+
className
+
RedisUtils
.
FIND_PAGE_KEY
+
MD5Tools
.
MD5
(
keyId
).
substring
(
0
,
20
);
}
public
static
String
getFindListKeyPattern
(
String
className
){
if
(
className
==
null
){
className
=
""
;}
return
RedisUtils
.
KEY_PREFIX
+
className
+
FIND_LIST_KEY_PATTERN
;
}
public
static
String
getFinPageKeyPattern
(
String
className
){
if
(
className
==
null
){
className
=
""
;}
return
RedisUtils
.
KEY_PREFIX
+
className
+
FIND_PAGE_KEY_PATTERN
;
}
/**
* 获取token的有效期(秒)
* @param key
*/
public
long
getExpireTime
(
String
key
){
long
time
=
redisTemplate
.
getExpire
(
key
,
TimeUnit
.
SECONDS
);
return
time
;
}
/**
* 批量删除对应的value
*
* @param keys
*/
public
void
remove
(
final
String
...
keys
)
{
if
(!
run
())
{
return
;
}
try
{
for
(
String
key
:
keys
)
{
remove
(
key
);
}
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils remove:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
}
/**
* 批量删除key
*
* @param pattern
*/
public
void
removePattern
(
String
pattern
)
{
if
(!
run
())
{
return
;}
if
(!
listFlush
()){
return
;
}
try
{
if
(
pattern
==
null
)
{
pattern
=
""
;
}
Set
<
String
>
keys
=
getKyes
(
pattern
);
if
(
keys
.
size
()
>
0
)
{
redisTemplate
.
delete
(
keys
);
}
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils removePattern:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
}
public
void
removePatternShiroReids
(
String
pattern
){
if
(!
run
())
{
return
;}
if
(!
listFlush
()){
return
;
}
try
{
if
(
pattern
==
null
)
{
pattern
=
""
;
}
Set
<
String
>
keys
=
getKyesShiroReids
(
pattern
);
if
(
keys
.
size
()
>
0
){
stringRedisTemplate
.
delete
(
keys
);
redisTemplate
.
delete
(
keys
);
}
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils removePattern:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
}
/**
* 获取keys
*
* @param pattern
*/
public
Set
<
String
>
getKyes
(
String
pattern
)
{
if
(!
run
())
{
return
null
;
}
try
{
if
(
pattern
==
null
){
pattern
=
""
;
}
Set
<
String
>
keys
=
stringRedisTemplate
.
keys
(
"*"
+
pattern
);
Set
<
String
>
keysnew
=
new
HashSet
<
String
>();
Iterator
<
String
>
it
=
keys
.
iterator
();
while
(
it
.
hasNext
())
{
keysnew
.
add
(
it
.
next
().
substring
(
7
));
}
return
keysnew
;
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils getKyes:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
e
.
getMessage
());
return
null
;
}
}
public
Set
<
String
>
getKyesShiroReids
(
String
pattern
)
{
if
(!
run
())
{
return
null
;
}
try
{
if
(
pattern
==
null
){
pattern
=
""
;
}
Set
<
String
>
keys
=
stringRedisTemplate
.
keys
(
"*"
+
pattern
);
Set
<
String
>
keysnew
=
new
HashSet
<
String
>();
Iterator
<
String
>
it
=
keys
.
iterator
();
while
(
it
.
hasNext
())
{
String
tr
=
it
.
next
();
if
(
tr
.
contains
(
SHIRO_REDIS
))
{
keysnew
.
add
(
tr
);
}
else
if
(
tr
.
contains
(
SHIRO_REDIS_OBJECT
))
{
keysnew
.
add
(
tr
.
substring
(
8
));
}
}
return
keysnew
;
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils getKyes:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
e
.
getMessage
());
return
null
;
}
}
public
Set
<
String
>
getKyesAll
()
{
if
(!
run
())
{
return
null
;
}
try
{
Set
<
String
>
keys
=
stringRedisTemplate
.
keys
(
"*"
);
Set
<
String
>
keysnew
=
new
HashSet
<
String
>();
Iterator
<
String
>
it
=
keys
.
iterator
();
while
(
it
.
hasNext
())
{
keysnew
.
add
(
it
.
next
());
}
return
keysnew
;
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils getKyes:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
e
.
getMessage
());
return
null
;
}
}
/**
* 获取Count
*
*/
public
int
getCount
()
{
if
(!
run
())
{
return
0
;
}
try
{
Set
<
String
>
keys
=
stringRedisTemplate
.
keys
(
"*"
);
return
keys
.
size
();
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils getCount:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
e
.
getMessage
());
return
0
;
}
}
public
int
getCountShiro
()
{
if
(!
run
())
{
return
0
;
}
try
{
Set
<
String
>
keys
=
stringRedisTemplate
.
keys
(
SHIRO_REDIS
+
"*"
);
return
keys
.
size
();
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils getCount:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
e
.
getMessage
());
return
0
;
}
}
/**
* 删除对应的value
*
* @param key
*/
public
void
remove
(
final
String
key
)
{
if
(!
run
())
{
return
;
}
try
{
if
(
key
.
contains
(
SHIRO_REDIS
))
{
stringRedisTemplate
.
delete
(
key
);
}
else
{
redisTemplate
.
delete
(
key
);
}
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils exists:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public
boolean
exists
(
final
String
key
)
{
if
(!
run
())
{
return
false
;
}
boolean
retuslt
=
false
;
try
{
if
(
key
.
contains
(
SHIRO_REDIS
))
{
retuslt
=
stringRedisTemplate
.
hasKey
(
key
);
}
else
{
retuslt
=
redisTemplate
.
hasKey
(
key
);
}
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils exists:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
return
retuslt
;
}
/**
* 读取缓存
*
* @param key
* @return
*/
public
Object
get
(
final
String
key
)
{
if
(!
run
())
{
return
null
;
}
Object
result
=
null
;
try
{
if
(
key
.
contains
(
SHIRO_REDIS
)){
ValueOperations
<
String
,
String
>
operationsString
=
stringRedisTemplate
.
opsForValue
();
result
=
operationsString
.
get
(
key
);
}
else
{
ValueOperations
<
Serializable
,
Object
>
operations
=
redisTemplate
.
opsForValue
();
result
=
operations
.
get
(
key
);
}
return
result
;
}
catch
(
Exception
e
){
logger
.
error
(
"RedisUtils get:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
return
result
;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public
boolean
set
(
final
String
key
,
Object
value
)
{
if
(!
run
())
{
return
false
;
}
boolean
result
=
false
;
try
{
ValueOperations
<
Serializable
,
Object
>
operations
=
redisTemplate
.
opsForValue
();
operations
.
set
(
key
,
value
);
redisTemplate
.
expire
(
key
,
expireTime
,
TimeUnit
.
SECONDS
);
result
=
true
;
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils set:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
return
result
;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public
boolean
set
(
final
String
key
,
Object
value
,
Long
expireTime
)
{
if
(!
run
())
{
return
false
;
}
boolean
result
=
false
;
try
{
ValueOperations
<
Serializable
,
Object
>
operations
=
redisTemplate
.
opsForValue
();
operations
.
set
(
key
,
value
);
redisTemplate
.
expire
(
key
,
expireTime
,
TimeUnit
.
SECONDS
);
result
=
true
;
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils set:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
return
result
;
}
public
boolean
set
(
final
String
key
,
Object
value
,
Long
expireTime
,
TimeUnit
unit
)
{
if
(!
run
())
{
return
false
;
}
boolean
result
=
false
;
try
{
ValueOperations
<
Serializable
,
Object
>
operations
=
redisTemplate
.
opsForValue
();
operations
.
set
(
key
,
value
);
redisTemplate
.
expire
(
key
,
expireTime
,
unit
);
result
=
true
;
}
catch
(
Exception
e
)
{
logger
.
error
(
"RedisUtils set:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
return
result
;
}
private
boolean
run
(){
if
(
Global
.
getConfig
(
"spring.redis.run"
)==
"true"
)
{
return
true
;
}
return
false
;
}
public
static
boolean
isRun
(){
if
(
Global
.
getConfig
(
"spring.redis.run"
)==
"true"
)
{
return
true
;
}
return
false
;
}
public
static
boolean
isShireRedis
(){
if
(
Global
.
getConfig
(
"spring.redis.run"
)!=
"true"
)
{
return
false
;
}
if
(
Global
.
getConfig
(
"shiro.redis"
)!=
"true"
)
{
return
false
;
}
return
true
;
}
private
boolean
listFlush
(){
if
(
Global
.
getConfig
(
"spring.redis.listFlush"
)==
"true"
)
{
return
true
;
}
return
false
;
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/common/security/Cryptos.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package
com.jeespring.common.security
;
import
java.io.UnsupportedEncodingException
;
import
java.security.GeneralSecurityException
;
import
java.security.SecureRandom
;
import
java.util.Arrays
;
import
javax.crypto.Cipher
;
import
javax.crypto.KeyGenerator
;
import
javax.crypto.Mac
;
import
javax.crypto.SecretKey
;
import
javax.crypto.spec.IvParameterSpec
;
import
javax.crypto.spec.SecretKeySpec
;
import
com.jeespring.common.utils.Encodes
;
import
com.jeespring.common.utils.Exceptions
;
/**
* 支持HMAC-SHA1消息签名 及 DES/AES对称加密的工具类.
*
* 支持Hex与Base64两种编码方式.
*
* @author calvin
*/
public
class
Cryptos
{
private
static
final
String
AES
=
"AES"
;
private
static
final
String
AES_CBC
=
"AES/CBC/PKCS5Padding"
;
private
static
final
String
HMACSHA1
=
"HmacSHA1"
;
private
static
final
String
DEFAULT_URL_ENCODING
=
"UTF-8"
;
private
static
final
int
DEFAULT_HMACSHA1_KEYSIZE
=
160
;
//RFC2401
private
static
final
int
DEFAULT_AES_KEYSIZE
=
128
;
private
static
final
int
DEFAULT_IVSIZE
=
16
;
private
static
final
byte
[]
DEFAULT_KEY
=
new
byte
[]{-
97
,
88
,-
94
,
9
,
70
,-
76
,
126
,
25
,
0
,
3
,-
20
,
113
,
108
,
28
,
69
,
125
};
private
static
SecureRandom
random
=
new
SecureRandom
();
//-- HMAC-SHA1 funciton --//
/**
* 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节.
*
* @param input 原始输入字符数组
* @param key HMAC-SHA1密钥
*/
public
static
byte
[]
hmacSha1
(
byte
[]
input
,
byte
[]
key
)
{
try
{
SecretKey
secretKey
=
new
SecretKeySpec
(
key
,
HMACSHA1
);
Mac
mac
=
Mac
.
getInstance
(
HMACSHA1
);
mac
.
init
(
secretKey
);
return
mac
.
doFinal
(
input
);
}
catch
(
GeneralSecurityException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
/**
* 校验HMAC-SHA1签名是否正确.
*
* @param expected 已存在的签名
* @param input 原始输入字符串
* @param key 密钥
*/
public
static
boolean
isMacValid
(
byte
[]
expected
,
byte
[]
input
,
byte
[]
key
)
{
byte
[]
actual
=
hmacSha1
(
input
,
key
);
return
Arrays
.
equals
(
expected
,
actual
);
}
/**
* 生成HMAC-SHA1密钥,返回字节数组,长度为160位(20字节).
* HMAC-SHA1算法对密钥无特殊要求, RFC2401建议最少长度为160位(20字节).
*/
public
static
byte
[]
generateHmacSha1Key
()
{
try
{
KeyGenerator
keyGenerator
=
KeyGenerator
.
getInstance
(
HMACSHA1
);
keyGenerator
.
init
(
DEFAULT_HMACSHA1_KEYSIZE
);
SecretKey
secretKey
=
keyGenerator
.
generateKey
();
return
secretKey
.
getEncoded
();
}
catch
(
GeneralSecurityException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
//-- AES funciton --//
/**
* 使用AES加密原始字符串.
*
* @param input 原始输入字符数组
*/
public
static
String
aesEncrypt
(
String
input
)
{
try
{
return
Encodes
.
encodeHex
(
aesEncrypt
(
input
.
getBytes
(
DEFAULT_URL_ENCODING
),
DEFAULT_KEY
));
}
catch
(
UnsupportedEncodingException
e
)
{
return
""
;
}
}
/**
* 使用AES加密原始字符串.
*
* @param input 原始输入字符数组
* @param key 符合AES要求的密钥
*/
public
static
String
aesEncrypt
(
String
input
,
String
key
)
{
try
{
return
Encodes
.
encodeHex
(
aesEncrypt
(
input
.
getBytes
(
DEFAULT_URL_ENCODING
),
Encodes
.
decodeHex
(
key
)));
}
catch
(
UnsupportedEncodingException
e
)
{
return
""
;
}
}
/**
* 使用AES加密原始字符串.
*
* @param input 原始输入字符数组
* @param key 符合AES要求的密钥
*/
public
static
byte
[]
aesEncrypt
(
byte
[]
input
,
byte
[]
key
)
{
return
aes
(
input
,
key
,
Cipher
.
ENCRYPT_MODE
);
}
/**
* 使用AES加密原始字符串.
*
* @param input 原始输入字符数组
* @param key 符合AES要求的密钥
* @param iv 初始向量
*/
public
static
byte
[]
aesEncrypt
(
byte
[]
input
,
byte
[]
key
,
byte
[]
iv
)
{
return
aes
(
input
,
key
,
iv
,
Cipher
.
ENCRYPT_MODE
);
}
/**
* 使用AES解密字符串, 返回原始字符串.
*
* @param input Hex编码的加密字符串
*/
public
static
String
aesDecrypt
(
String
input
)
{
try
{
return
new
String
(
aesDecrypt
(
Encodes
.
decodeHex
(
input
),
DEFAULT_KEY
),
DEFAULT_URL_ENCODING
);
}
catch
(
UnsupportedEncodingException
e
)
{
return
""
;
}
}
/**
* 使用AES解密字符串, 返回原始字符串.
*
* @param input Hex编码的加密字符串
* @param key 符合AES要求的密钥
*/
public
static
String
aesDecrypt
(
String
input
,
String
key
)
{
try
{
return
new
String
(
aesDecrypt
(
Encodes
.
decodeHex
(
input
),
Encodes
.
decodeHex
(
key
)),
DEFAULT_URL_ENCODING
);
}
catch
(
UnsupportedEncodingException
e
)
{
return
""
;
}
}
/**
* 使用AES解密字符串, 返回原始字符串.
*
* @param input Hex编码的加密字符串
* @param key 符合AES要求的密钥
*/
public
static
byte
[]
aesDecrypt
(
byte
[]
input
,
byte
[]
key
)
{
return
aes
(
input
,
key
,
Cipher
.
DECRYPT_MODE
);
}
/**
* 使用AES解密字符串, 返回原始字符串.
*
* @param input Hex编码的加密字符串
* @param key 符合AES要求的密钥
* @param iv 初始向量
*/
public
static
byte
[]
aesDecrypt
(
byte
[]
input
,
byte
[]
key
,
byte
[]
iv
)
{
return
aes
(
input
,
key
,
iv
,
Cipher
.
DECRYPT_MODE
);
}
/**
* 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
*
* @param input 原始字节数组
* @param key 符合AES要求的密钥
* @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
*/
private
static
byte
[]
aes
(
byte
[]
input
,
byte
[]
key
,
int
mode
)
{
try
{
SecretKey
secretKey
=
new
SecretKeySpec
(
key
,
AES
);
Cipher
cipher
=
Cipher
.
getInstance
(
AES
);
cipher
.
init
(
mode
,
secretKey
);
return
cipher
.
doFinal
(
input
);
}
catch
(
GeneralSecurityException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
/**
* 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
*
* @param input 原始字节数组
* @param key 符合AES要求的密钥
* @param iv 初始向量
* @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
*/
private
static
byte
[]
aes
(
byte
[]
input
,
byte
[]
key
,
byte
[]
iv
,
int
mode
)
{
try
{
SecretKey
secretKey
=
new
SecretKeySpec
(
key
,
AES
);
IvParameterSpec
ivSpec
=
new
IvParameterSpec
(
iv
);
Cipher
cipher
=
Cipher
.
getInstance
(
AES_CBC
);
cipher
.
init
(
mode
,
secretKey
,
ivSpec
);
return
cipher
.
doFinal
(
input
);
}
catch
(
GeneralSecurityException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
/**
* 生成AES密钥,返回字节数组, 默认长度为128位(16字节).
*/
public
static
String
generateAesKeyString
()
{
return
Encodes
.
encodeHex
(
generateAesKey
(
DEFAULT_AES_KEYSIZE
));
}
/**
* 生成AES密钥,返回字节数组, 默认长度为128位(16字节).
*/
public
static
byte
[]
generateAesKey
()
{
return
generateAesKey
(
DEFAULT_AES_KEYSIZE
);
}
/**
* 生成AES密钥,可选长度为128,192,256位.
*/
public
static
byte
[]
generateAesKey
(
int
keysize
)
{
try
{
KeyGenerator
keyGenerator
=
KeyGenerator
.
getInstance
(
AES
);
keyGenerator
.
init
(
keysize
);
SecretKey
secretKey
=
keyGenerator
.
generateKey
();
return
secretKey
.
getEncoded
();
}
catch
(
GeneralSecurityException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
/**
* 生成随机向量,默认大小为cipher.getBlockSize(), 16字节.
*/
public
static
byte
[]
generateIV
()
{
byte
[]
bytes
=
new
byte
[
DEFAULT_IVSIZE
];
random
.
nextBytes
(
bytes
);
return
bytes
;
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/common/security/Digests.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package
com.jeespring.common.security
;
import
java.io.IOException
;
import
java.io.InputStream
;
import
java.security.GeneralSecurityException
;
import
java.security.MessageDigest
;
import
java.security.SecureRandom
;
import
org.apache.commons.lang3.Validate
;
import
com.jeespring.common.utils.Exceptions
;
/**
* 支持SHA-1/MD5消息摘要的工具类.
*
* 返回ByteSource,可进一步被编码为Hex, Base64或UrlSafeBase64
*
* @author JeeSpring
*/
public
class
Digests
{
private
static
final
String
SHA1
=
"SHA-1"
;
private
static
final
String
MD5
=
"MD5"
;
private
static
SecureRandom
random
=
new
SecureRandom
();
/**
* 对输入字符串进行md5散列.
*/
public
static
byte
[]
md5
(
byte
[]
input
)
{
return
digest
(
input
,
MD5
,
null
,
1
);
}
public
static
byte
[]
md5
(
byte
[]
input
,
int
iterations
)
{
return
digest
(
input
,
MD5
,
null
,
iterations
);
}
/**
* 对输入字符串进行sha1散列.
*/
public
static
byte
[]
sha1
(
byte
[]
input
)
{
return
digest
(
input
,
SHA1
,
null
,
1
);
}
public
static
byte
[]
sha1
(
byte
[]
input
,
byte
[]
salt
)
{
return
digest
(
input
,
SHA1
,
salt
,
1
);
}
public
static
byte
[]
sha1
(
byte
[]
input
,
byte
[]
salt
,
int
iterations
)
{
return
digest
(
input
,
SHA1
,
salt
,
iterations
);
}
/**
* 对字符串进行散列, 支持md5与sha1算法.
*/
private
static
byte
[]
digest
(
byte
[]
input
,
String
algorithm
,
byte
[]
salt
,
int
iterations
)
{
try
{
MessageDigest
digest
=
MessageDigest
.
getInstance
(
algorithm
);
if
(
salt
!=
null
)
{
digest
.
update
(
salt
);
}
byte
[]
result
=
digest
.
digest
(
input
);
for
(
int
i
=
1
;
i
<
iterations
;
i
++)
{
digest
.
reset
();
result
=
digest
.
digest
(
result
);
}
return
result
;
}
catch
(
GeneralSecurityException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
/**
* 生成随机的Byte[]作为salt.
*
* @param numBytes byte数组的大小
*/
public
static
byte
[]
generateSalt
(
int
numBytes
)
{
Validate
.
isTrue
(
numBytes
>
0
,
"numBytes argument must be a positive integer (1 or larger)"
,
numBytes
);
byte
[]
bytes
=
new
byte
[
numBytes
];
random
.
nextBytes
(
bytes
);
return
bytes
;
}
/**
* 对文件进行md5散列.
*/
public
static
byte
[]
md5
(
InputStream
input
)
throws
IOException
{
return
digest
(
input
,
MD5
);
}
/**
* 对文件进行sha1散列.
*/
public
static
byte
[]
sha1
(
InputStream
input
)
throws
IOException
{
return
digest
(
input
,
SHA1
);
}
private
static
byte
[]
digest
(
InputStream
input
,
String
algorithm
)
throws
IOException
{
try
{
MessageDigest
messageDigest
=
MessageDigest
.
getInstance
(
algorithm
);
int
bufferLength
=
8
*
1024
;
byte
[]
buffer
=
new
byte
[
bufferLength
];
int
read
=
input
.
read
(
buffer
,
0
,
bufferLength
);
while
(
read
>
-
1
)
{
messageDigest
.
update
(
buffer
,
0
,
read
);
read
=
input
.
read
(
buffer
,
0
,
bufferLength
);
}
return
messageDigest
.
digest
();
}
catch
(
GeneralSecurityException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
public
static
String
string2MD5
(
String
inStr
){
MessageDigest
md5
=
null
;
try
{
md5
=
MessageDigest
.
getInstance
(
"MD5"
);
}
catch
(
Exception
e
){
System
.
out
.
println
(
e
.
toString
());
e
.
printStackTrace
();
return
""
;
}
char
[]
charArray
=
inStr
.
toCharArray
();
byte
[]
byteArray
=
new
byte
[
charArray
.
length
];
for
(
int
i
=
0
;
i
<
charArray
.
length
;
i
++)
{
byteArray
[
i
]
=
(
byte
)
charArray
[
i
];
}
byte
[]
md5Bytes
=
md5
.
digest
(
byteArray
);
StringBuffer
hexValue
=
new
StringBuffer
();
for
(
int
i
=
0
;
i
<
md5Bytes
.
length
;
i
++){
int
val
=
((
int
)
md5Bytes
[
i
])
&
0xff
;
if
(
val
<
16
)
{
hexValue
.
append
(
"0"
);
}
hexValue
.
append
(
Integer
.
toHexString
(
val
));
}
return
hexValue
.
toString
();
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/security/MD5Tools.java
0 → 100644
View file @
d5ba54ba
package
com.jeespring.common.security
;
import
java.security.MessageDigest
;
/**
* MD5加密工具类
* <功能详细描述>
*
* @author chenlujun
* @version [版本号, 2014年10月1日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public
class
MD5Tools
{
public
final
static
String
MD5
(
String
pwd
)
{
//用于加密的字符
char
[]
md5String
=
{
'0'
,
'1'
,
'2'
,
'3'
,
'4'
,
'5'
,
'6'
,
'7'
,
'8'
,
'9'
,
'A'
,
'B'
,
'C'
,
'D'
,
'E'
,
'F'
};
try
{
//使用平台的默认字符集将此 String 编码为 byte序列,并将结果存储到一个新的 byte数组中
byte
[]
btInput
=
pwd
.
getBytes
();
//信息摘要是安全的单向哈希函数,它接收任意大小的数据,并输出固定长度的哈希值。
MessageDigest
mdInst
=
MessageDigest
.
getInstance
(
"MD5"
);
//MessageDigest对象通过使用 update方法处理数据, 使用指定的byte数组更新摘要
mdInst
.
update
(
btInput
);
// 摘要更新之后,通过调用digest()执行哈希计算,获得密文
byte
[]
md
=
mdInst
.
digest
();
// 把密文转换成十六进制的字符串形式
int
j
=
md
.
length
;
char
[]
str
=
new
char
[
j
*
2
];
int
k
=
0
;
for
(
int
i
=
0
;
i
<
j
;
i
++)
{
// i = 0
byte
byte0
=
md
[
i
];
//95
str
[
k
++]
=
md5String
[
byte0
>>>
4
&
0xf
];
// 5
str
[
k
++]
=
md5String
[
byte0
&
0xf
];
// F
}
//返回经过加密后的字符串
return
new
String
(
str
);
}
catch
(
Exception
e
)
{
return
null
;
}
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/common/security/ShiroUtils.java
0 → 100644
View file @
d5ba54ba
package
com.jeespring.common.security
;
import
com.jeespring.modules.sys.entity.User
;
import
com.jeespring.modules.sys.entity.UserRealm
;
import
org.apache.shiro.SecurityUtils
;
import
org.apache.shiro.mgt.RealmSecurityManager
;
import
org.apache.shiro.session.Session
;
import
org.apache.shiro.subject.PrincipalCollection
;
import
org.apache.shiro.subject.SimplePrincipalCollection
;
import
org.apache.shiro.subject.Subject
;
import
com.jeespring.common.utils.StringUtils
;
import
com.jeespring.common.utils.bean.BeanUtils
;
/**
* shiro 工具类
*
* @author JeeSpring
*/
public
class
ShiroUtils
{
public
static
Subject
getSubjct
()
{
return
SecurityUtils
.
getSubject
();
}
public
static
Session
getSession
()
{
return
SecurityUtils
.
getSubject
().
getSession
();
}
public
static
void
logout
()
{
getSubjct
().
logout
();
}
public
static
User
getUser
()
{
User
user
=
null
;
Object
obj
=
getSubjct
().
getPrincipal
();
if
(
StringUtils
.
isNotNull
(
obj
))
{
user
=
new
User
();
BeanUtils
.
copyBeanProp
(
user
,
obj
);
}
return
user
;
}
public
static
void
setUser
(
User
user
)
{
Subject
subject
=
getSubjct
();
PrincipalCollection
principalCollection
=
subject
.
getPrincipals
();
String
realmName
=
principalCollection
.
getRealmNames
().
iterator
().
next
();
PrincipalCollection
newPrincipalCollection
=
new
SimplePrincipalCollection
(
user
,
realmName
);
// 重新加载Principal
subject
.
runAs
(
newPrincipalCollection
);
}
public
static
void
clearCachedAuthorizationInfo
()
{
RealmSecurityManager
rsm
=
(
RealmSecurityManager
)
SecurityUtils
.
getSecurityManager
();
UserRealm
realm
=
(
UserRealm
)
rsm
.
getRealms
().
iterator
().
next
();
realm
.
clearCachedAuthorizationInfo
();
}
public
static
Long
getUserId
()
{
return
Long
.
valueOf
(
getUser
().
getId
());
}
public
static
String
getLoginName
()
{
return
getUser
().
getLoginName
();
}
public
static
String
getIp
()
{
return
getSubjct
().
getSession
().
getHost
();
}
public
static
String
getSessionId
()
{
return
String
.
valueOf
(
getSubjct
().
getSession
().
getId
());
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/security/shiro/HasAnyPermissionsTag.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.security.shiro
;
import
org.apache.shiro.subject.Subject
;
import
org.apache.shiro.web.tags.PermissionTag
;
/**
* Shiro HasAnyPermissions Tag.
*
* @author calvin
*/
public
class
HasAnyPermissionsTag
extends
PermissionTag
{
private
static
final
long
serialVersionUID
=
1L
;
private
static
final
String
PERMISSION_NAMES_DELIMETER
=
","
;
@Override
protected
boolean
showTagBody
(
String
permissionNames
)
{
boolean
hasAnyPermission
=
false
;
Subject
subject
=
getSubject
();
if
(
subject
!=
null
)
{
// Iterate through permissions and check to see if the user has one of the permissions
for
(
String
permission
:
permissionNames
.
split
(
PERMISSION_NAMES_DELIMETER
))
{
if
(
subject
.
isPermitted
(
permission
.
trim
()))
{
hasAnyPermission
=
true
;
break
;
}
}
}
return
hasAnyPermission
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/security/shiro/cache/SessionCacheManager.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.security.shiro.cache
;
import
java.util.Collection
;
import
java.util.Collections
;
import
java.util.Set
;
import
javax.servlet.http.HttpServletRequest
;
import
org.apache.shiro.SecurityUtils
;
import
org.apache.shiro.UnavailableSecurityManagerException
;
import
org.apache.shiro.cache.Cache
;
import
org.apache.shiro.cache.CacheException
;
import
org.apache.shiro.cache.CacheManager
;
import
org.apache.shiro.session.InvalidSessionException
;
import
org.apache.shiro.session.Session
;
import
org.apache.shiro.subject.Subject
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
com.google.common.collect.Sets
;
import
com.jeespring.common.web.Servlets
;
/**
* 自定义授权缓存管理类
* @author 黄炳桂 516821420@qq.com
* @version 2014-7-21
*/
public
class
SessionCacheManager
implements
CacheManager
{
@Override
public
<
K
,
V
>
Cache
<
K
,
V
>
getCache
(
String
name
)
throws
CacheException
{
return
new
SessionCache
<
K
,
V
>(
name
);
}
/**
* SESSION缓存管理类
*/
public
class
SessionCache
<
K
,
V
>
implements
Cache
<
K
,
V
>
{
private
Logger
logger
=
LoggerFactory
.
getLogger
(
getClass
());
private
String
cacheKeyName
=
null
;
public
SessionCache
(
String
cacheKeyName
)
{
this
.
cacheKeyName
=
cacheKeyName
;
}
public
Session
getSession
(){
Session
session
=
null
;
try
{
Subject
subject
=
SecurityUtils
.
getSubject
();
session
=
subject
.
getSession
(
false
);
if
(
session
==
null
){
session
=
subject
.
getSession
();
}
}
catch
(
InvalidSessionException
e
){
logger
.
error
(
"Invalid session error"
,
e
);
}
catch
(
UnavailableSecurityManagerException
e2
){
logger
.
error
(
"Unavailable SecurityManager error"
,
e2
);
}
return
session
;
}
@SuppressWarnings
(
"unchecked"
)
@Override
public
V
get
(
K
key
)
throws
CacheException
{
if
(
key
==
null
){
return
null
;
}
V
v
=
null
;
HttpServletRequest
request
=
Servlets
.
getRequest
();
if
(
request
!=
null
){
v
=
(
V
)
request
.
getAttribute
(
cacheKeyName
);
if
(
v
!=
null
){
return
v
;
}
}
V
value
=
null
;
value
=
(
V
)
getSession
().
getAttribute
(
cacheKeyName
);
logger
.
debug
(
"get {} {} {}"
,
cacheKeyName
,
key
,
request
!=
null
?
request
.
getRequestURI
()
:
""
);
if
(
request
!=
null
&&
value
!=
null
){
request
.
setAttribute
(
cacheKeyName
,
value
);
}
return
value
;
}
@Override
public
V
put
(
K
key
,
V
value
)
throws
CacheException
{
if
(
key
==
null
){
return
null
;
}
getSession
().
setAttribute
(
cacheKeyName
,
value
);
if
(
logger
.
isDebugEnabled
()){
HttpServletRequest
request
=
Servlets
.
getRequest
();
logger
.
debug
(
"put {} {} {}"
,
cacheKeyName
,
key
,
request
!=
null
?
request
.
getRequestURI
()
:
""
);
}
return
value
;
}
@SuppressWarnings
(
"unchecked"
)
@Override
public
V
remove
(
K
key
)
throws
CacheException
{
V
value
=
null
;
value
=
(
V
)
getSession
().
removeAttribute
(
cacheKeyName
);
logger
.
debug
(
"remove {} {}"
,
cacheKeyName
,
key
);
return
value
;
}
@Override
public
void
clear
()
throws
CacheException
{
getSession
().
removeAttribute
(
cacheKeyName
);
logger
.
debug
(
"clear {}"
,
cacheKeyName
);
}
@Override
public
int
size
()
{
logger
.
debug
(
"invoke session size abstract size method not supported."
);
return
0
;
}
@Override
public
Set
<
K
>
keys
()
{
logger
.
debug
(
"invoke session keys abstract size method not supported."
);
return
Sets
.
newHashSet
();
}
@Override
public
Collection
<
V
>
values
()
{
logger
.
debug
(
"invoke session values abstract size method not supported."
);
return
Collections
.
emptyList
();
}
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/security/shiro/session/CacheSessionDAO.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.security.shiro.session
;
import
java.io.Serializable
;
import
java.util.Collection
;
import
java.util.Set
;
import
javax.servlet.http.HttpServletRequest
;
import
org.apache.shiro.cache.CacheManager
;
import
org.apache.shiro.session.Session
;
import
org.apache.shiro.session.UnknownSessionException
;
import
org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
;
import
org.apache.shiro.subject.PrincipalCollection
;
import
org.apache.shiro.subject.support.DefaultSubjectContext
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.beans.factory.InitializingBean
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.stereotype.Component
;
import
com.google.common.collect.Sets
;
import
com.jeespring.common.config.Global
;
import
com.jeespring.common.utils.DateUtils
;
import
com.jeespring.common.utils.IdGen
;
import
com.jeespring.common.utils.StringUtils
;
import
com.jeespring.common.web.Servlets
;
/**
* 系统安全认证实现类
* @author 黄炳桂 516821420@qq.com
* @version 2014-7-24
*/
@Component
(
"sessionDAO"
)
public
class
CacheSessionDAO
extends
EnterpriseCacheSessionDAO
implements
SessionDAO
,
InitializingBean
{
private
Logger
logger
=
LoggerFactory
.
getLogger
(
getClass
());
@Autowired
private
IdGen
idgen
;
@Autowired
private
CacheManager
cacheManager
;
@Override
public
void
afterPropertiesSet
()
throws
Exception
{
setSessionIdGenerator
(
idgen
);
setActiveSessionsCacheName
(
"activeSessionsCache"
);
setCacheManager
(
cacheManager
);
}
public
CacheSessionDAO
()
{
super
();
}
@Override
protected
void
doUpdate
(
Session
session
)
{
if
(
session
==
null
||
session
.
getId
()
==
null
)
{
return
;
}
HttpServletRequest
request
=
Servlets
.
getRequest
();
if
(
request
!=
null
){
String
uri
=
request
.
getServletPath
();
// 如果是静态文件,则不更新SESSION
if
(
Servlets
.
isStaticFile
(
uri
)){
return
;
}
// 如果是视图文件,则不更新SESSION
if
(
StringUtils
.
startsWith
(
uri
,
Global
.
getConfig
(
"spring.mvc.view.prefix"
))
&&
StringUtils
.
endsWith
(
uri
,
Global
.
getConfig
(
"spring.mvc.view.suffix"
))){
return
;
}
// 手动控制不更新SESSION
String
updateSession
=
request
.
getParameter
(
"updateSession"
);
if
(
Global
.
FALSE
.
equals
(
updateSession
)
||
Global
.
NO
.
equals
(
updateSession
)){
return
;
}
}
super
.
doUpdate
(
session
);
logger
.
debug
(
"update {} {}"
,
session
.
getId
(),
request
!=
null
?
request
.
getRequestURI
()
:
""
);
}
@Override
protected
void
doDelete
(
Session
session
)
{
if
(
session
==
null
||
session
.
getId
()
==
null
)
{
return
;
}
super
.
doDelete
(
session
);
logger
.
debug
(
"delete {} "
,
session
.
getId
());
}
@Override
protected
Serializable
doCreate
(
Session
session
)
{
HttpServletRequest
request
=
Servlets
.
getRequest
();
if
(
request
!=
null
){
String
uri
=
request
.
getServletPath
();
// 如果是静态文件,则不创建SESSION
if
(
Servlets
.
isStaticFile
(
uri
)){
return
null
;
}
}
super
.
doCreate
(
session
);
logger
.
debug
(
"doCreate {} {}"
,
session
,
request
!=
null
?
request
.
getRequestURI
()
:
""
);
return
session
.
getId
();
}
@Override
protected
Session
doReadSession
(
Serializable
sessionId
)
{
return
super
.
doReadSession
(
sessionId
);
}
@Override
public
Session
readSession
(
Serializable
sessionId
)
throws
UnknownSessionException
{
try
{
Session
s
=
null
;
HttpServletRequest
request
=
Servlets
.
getRequest
();
if
(
request
!=
null
){
String
uri
=
request
.
getServletPath
();
// 如果是静态文件,则不获取SESSION
if
(
Servlets
.
isStaticFile
(
uri
)){
return
null
;
}
s
=
(
Session
)
request
.
getAttribute
(
"session_"
+
sessionId
);
}
if
(
s
!=
null
){
return
s
;
}
Session
session
=
super
.
readSession
(
sessionId
);
logger
.
debug
(
"readSession {} {}"
,
sessionId
,
request
!=
null
?
request
.
getRequestURI
()
:
""
);
if
(
request
!=
null
&&
session
!=
null
){
request
.
setAttribute
(
"session_"
+
sessionId
,
session
);
}
return
session
;
}
catch
(
UnknownSessionException
e
)
{
return
null
;
}
}
/**
* 获取活动会话
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @return
*/
@Override
public
Collection
<
Session
>
getActiveSessions
(
boolean
includeLeave
)
{
return
getActiveSessions
(
includeLeave
,
null
,
null
);
}
/**
* 获取活动会话
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @param principal 根据登录者对象获取活动会话
* @param filterSession 不为空,则过滤掉(不包含)这个会话。
* @return
*/
@Override
public
Collection
<
Session
>
getActiveSessions
(
boolean
includeLeave
,
Object
principal
,
Session
filterSession
)
{
// 如果包括离线,并无登录者条件。
if
(
includeLeave
&&
principal
==
null
){
return
getActiveSessions
();
}
Set
<
Session
>
sessions
=
Sets
.
newHashSet
();
for
(
Session
session
:
getActiveSessions
()){
boolean
isActiveSession
=
false
;
// 不包括离线并符合最后访问时间小于等于3分钟条件。
if
(
includeLeave
||
DateUtils
.
pastMinutes
(
session
.
getLastAccessTime
())
<=
3
){
isActiveSession
=
true
;
}
// 符合登陆者条件。
if
(
principal
!=
null
){
PrincipalCollection
pc
=
(
PrincipalCollection
)
session
.
getAttribute
(
DefaultSubjectContext
.
PRINCIPALS_SESSION_KEY
);
if
(
principal
.
toString
().
equals
(
pc
!=
null
?
pc
.
getPrimaryPrincipal
().
toString
()
:
StringUtils
.
EMPTY
)){
isActiveSession
=
true
;
}
}
// 过滤掉的SESSION
if
(
filterSession
!=
null
&&
filterSession
.
getId
().
equals
(
session
.
getId
())){
isActiveSession
=
false
;
}
if
(
isActiveSession
){
sessions
.
add
(
session
);
}
}
return
sessions
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/security/shiro/session/SessionDAO.java
0 → 100644
View file @
d5ba54ba
package
com.jeespring.common.security.shiro.session
;
import
java.util.Collection
;
import
org.apache.shiro.session.Session
;
public
interface
SessionDAO
extends
org
.
apache
.
shiro
.
session
.
mgt
.
eis
.
SessionDAO
{
/**
* 获取活动会话
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @return
*/
Collection
<
Session
>
getActiveSessions
(
boolean
includeLeave
);
/**
* 获取活动会话
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @param principal 根据登录者对象获取活动会话
* @param filterSession 不为空,则过滤掉(不包含)这个会话。
* @return
*/
Collection
<
Session
>
getActiveSessions
(
boolean
includeLeave
,
Object
principal
,
Session
filterSession
);
}
JeeSpringCloud/src/main/java/com/jeespring/common/security/shiro/session/SessionManager.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.security.shiro.session
;
import
java.io.Serializable
;
import
java.util.Collection
;
import
java.util.Date
;
import
javax.servlet.ServletRequest
;
import
javax.servlet.ServletResponse
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
com.jeespring.common.utils.StringUtils
;
import
org.apache.shiro.session.InvalidSessionException
;
import
org.apache.shiro.session.Session
;
import
org.apache.shiro.session.UnknownSessionException
;
import
org.apache.shiro.session.mgt.SessionContext
;
import
org.apache.shiro.session.mgt.SessionKey
;
import
org.apache.shiro.session.mgt.SimpleSession
;
import
org.apache.shiro.web.servlet.Cookie
;
import
org.apache.shiro.web.servlet.ShiroHttpServletRequest
;
import
org.apache.shiro.web.servlet.SimpleCookie
;
import
org.apache.shiro.web.session.mgt.DefaultWebSessionManager
;
import
org.apache.shiro.web.util.WebUtils
;
import
org.springframework.stereotype.Component
;
/**
* 自定义WEB会话管理类
* @author 黄炳桂 516821420@qq.com
* @version 2014-7-20
*/
@Component
public
class
SessionManager
extends
DefaultWebSessionManager
{
public
SessionManager
()
{
super
();
}
@Override
protected
Serializable
getSessionId
(
ServletRequest
request
,
ServletResponse
response
)
{
// 如果参数中包含“__sid”参数,则使用此sid会话。 例如:http://localhost/project?__sid=xxx&__cookie=true
String
sid
=
request
.
getParameter
(
"__sid"
);
if
(
StringUtils
.
isNotBlank
(
sid
))
{
// 是否将sid保存到cookie,浏览器模式下使用此参数。
if
(
WebUtils
.
isTrue
(
request
,
"__cookie"
)){
HttpServletRequest
rq
=
(
HttpServletRequest
)
request
;
HttpServletResponse
rs
=
(
HttpServletResponse
)
response
;
Cookie
template
=
getSessionIdCookie
();
Cookie
cookie
=
new
SimpleCookie
(
template
);
cookie
.
setValue
(
sid
);
cookie
.
saveTo
(
rq
,
rs
);
}
// 设置当前session状态
request
.
setAttribute
(
ShiroHttpServletRequest
.
REFERENCED_SESSION_ID_SOURCE
,
ShiroHttpServletRequest
.
URL_SESSION_ID_SOURCE
);
// session来源与url
request
.
setAttribute
(
ShiroHttpServletRequest
.
REFERENCED_SESSION_ID
,
sid
);
request
.
setAttribute
(
ShiroHttpServletRequest
.
REFERENCED_SESSION_ID_IS_VALID
,
Boolean
.
TRUE
);
return
sid
;
}
else
{
return
super
.
getSessionId
(
request
,
response
);
}
}
@Override
public
void
validateSessions
()
{
super
.
validateSessions
();
}
@Override
protected
Session
retrieveSession
(
SessionKey
sessionKey
)
{
try
{
return
super
.
retrieveSession
(
sessionKey
);
}
catch
(
UnknownSessionException
e
)
{
// 获取不到SESSION不抛出异常
return
null
;
}
}
@Override
public
Date
getStartTimestamp
(
SessionKey
key
)
{
try
{
return
super
.
getStartTimestamp
(
key
);
}
catch
(
InvalidSessionException
e
)
{
// 获取不到SESSION不抛出异常
return
null
;
}
}
@Override
public
Date
getLastAccessTime
(
SessionKey
key
)
{
try
{
return
super
.
getLastAccessTime
(
key
);
}
catch
(
InvalidSessionException
e
)
{
// 获取不到SESSION不抛出异常
return
null
;
}
}
@Override
public
long
getTimeout
(
SessionKey
key
){
try
{
return
super
.
getTimeout
(
key
);
}
catch
(
InvalidSessionException
e
)
{
// 获取不到SESSION不抛出异常
return
0
;
}
}
@Override
public
void
setTimeout
(
SessionKey
key
,
long
maxIdleTimeInMillis
)
{
try
{
super
.
setTimeout
(
key
,
maxIdleTimeInMillis
);
}
catch
(
InvalidSessionException
e
)
{
// 获取不到SESSION不抛出异常
}
}
@Override
public
void
touch
(
SessionKey
key
)
{
try
{
super
.
touch
(
key
);
}
catch
(
InvalidSessionException
e
)
{
// 获取不到SESSION不抛出异常
}
}
@Override
public
String
getHost
(
SessionKey
key
)
{
try
{
return
super
.
getHost
(
key
);
}
catch
(
InvalidSessionException
e
)
{
// 获取不到SESSION不抛出异常
return
null
;
}
}
@Override
public
Collection
<
Object
>
getAttributeKeys
(
SessionKey
key
)
{
try
{
return
super
.
getAttributeKeys
(
key
);
}
catch
(
InvalidSessionException
e
)
{
// 获取不到SESSION不抛出异常
return
null
;
}
}
@Override
public
Object
getAttribute
(
SessionKey
sessionKey
,
Object
attributeKey
)
{
try
{
return
super
.
getAttribute
(
sessionKey
,
attributeKey
);
}
catch
(
InvalidSessionException
e
)
{
// 获取不到SESSION不抛出异常
return
null
;
}
}
@Override
public
void
setAttribute
(
SessionKey
sessionKey
,
Object
attributeKey
,
Object
value
)
{
try
{
super
.
setAttribute
(
sessionKey
,
attributeKey
,
value
);
}
catch
(
InvalidSessionException
e
)
{
// 获取不到SESSION不抛出异常
}
}
@Override
public
Object
removeAttribute
(
SessionKey
sessionKey
,
Object
attributeKey
)
{
try
{
return
super
.
removeAttribute
(
sessionKey
,
attributeKey
);
}
catch
(
InvalidSessionException
e
)
{
// 获取不到SESSION不抛出异常
return
null
;
}
}
@Override
public
void
stop
(
SessionKey
key
)
{
try
{
super
.
stop
(
key
);
}
catch
(
InvalidSessionException
e
)
{
// 获取不到SESSION不抛出异常
}
}
@Override
public
void
checkValid
(
SessionKey
key
)
{
try
{
super
.
checkValid
(
key
);
}
catch
(
InvalidSessionException
e
)
{
// 获取不到SESSION不抛出异常
}
}
@Override
protected
Session
doCreateSession
(
SessionContext
context
)
{
try
{
return
super
.
doCreateSession
(
context
);
}
catch
(
IllegalStateException
e
)
{
return
null
;
}
}
@Override
protected
Session
newSessionInstance
(
SessionContext
context
)
{
Session
session
=
super
.
newSessionInstance
(
context
);
session
.
setTimeout
(
getGlobalSessionTimeout
());
return
session
;
}
@Override
public
Session
start
(
SessionContext
context
)
{
try
{
return
super
.
start
(
context
);
}
catch
(
NullPointerException
e
)
{
SimpleSession
session
=
new
SimpleSession
();
session
.
setId
(
0
);
return
session
;
}
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/common/service/AbstractBaseService.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.service
;
import
com.jeespring.common.persistence.InterfaceBaseDao
;
import
com.jeespring.common.persistence.AbstractBaseEntity
;
import
com.jeespring.common.persistence.Page
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.transaction.annotation.Transactional
;
import
java.util.List
;
/**
* Service基类
*
* @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
*/
@Transactional
(
readOnly
=
true
)
public
abstract
class
AbstractBaseService
<
Dao
extends
InterfaceBaseDao
<
T
>,
T
extends
AbstractBaseEntity
<
T
>>
extends
AbstractService
{
/**
* 持久层对象
*/
@Autowired
protected
Dao
dao
;
/**
* 获取单条数据
*
* @param id
* @return
*/
public
T
get
(
String
id
)
{
return
dao
.
get
(
id
);
}
/**
* 获取单条数据
*
* @param entity
* @return
*/
public
T
get
(
T
entity
)
{
return
dao
.
get
(
entity
);
}
/**
* 查询统计数据
*
* @param entity
* @return
*/
public
List
<
T
>
total
(
T
entity
)
{
return
dao
.
total
(
entity
);
}
/**
* 查询列表数据
*
* @param entity
* @return
*/
public
List
<
T
>
findList
(
T
entity
)
{
return
dao
.
findList
(
entity
);
}
/**
* 查询所有
*
* @param entity
* @return
*/
public
List
<
T
>
findAllList
(
T
entity
)
{
return
dao
.
findAllList
(
entity
);
}
/**
* 查询分页数据
*
* @param page 分页对象
* @param entity
* @return
*/
public
Page
<
T
>
findPage
(
Page
<
T
>
page
,
T
entity
)
{
entity
.
setPage
(
page
);
page
.
setList
(
dao
.
findList
(
entity
));
return
page
;
}
/**
* 保存数据(插入或更新)
*
* @param entity
*/
@Transactional
(
readOnly
=
false
)
public
void
save
(
T
entity
)
{
int
result
=
0
;
if
(
entity
.
getIsNewRecord
())
{
entity
.
preInsert
();
result
=
dao
.
insert
(
entity
);
}
else
{
entity
.
preUpdate
();
result
=
dao
.
update
(
entity
);
}
}
/**
* 删除数据
*
* @param entity
*/
@Transactional
(
readOnly
=
false
)
public
void
delete
(
T
entity
)
{
dao
.
delete
(
entity
);
}
/**
* 删除数据(逻辑删除,更新del_flag字段为1,在表包含字段del_flag时,可以调用此方法,将数据隐藏)
* @param entity
* @return
*/
@Transactional
(
readOnly
=
false
)
public
void
deleteByLogic
(
T
entity
)
{
dao
.
deleteByLogic
(
entity
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/service/AbstractService.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.service
;
import
java.util.List
;
import
com.jeespring.common.persistence.AbstractEntity
;
import
com.jeespring.common.utils.StringUtils
;
import
com.jeespring.modules.sys.entity.Role
;
import
com.jeespring.modules.sys.entity.User
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.transaction.annotation.Transactional
;
import
com.google.common.collect.Lists
;
/**
* Service基类
* @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
*/
@Transactional
(
readOnly
=
true
)
public
abstract
class
AbstractService
implements
InterfaceService
{
/**
* 日志对象
*/
protected
Logger
logger
=
LoggerFactory
.
getLogger
(
getClass
());
/**
* 数据范围过滤
* @param user 当前用户对象,通过“entity.getCurrentUser()”获取
* @param officeAlias 机构表别名,多个用“,”逗号隔开。
* @param userAlias 用户表别名,多个用“,”逗号隔开,传递空,忽略此参数
* @return 标准连接条件对象
*/
public
static
String
dataScopeFilter
(
User
user
,
String
officeAlias
,
String
userAlias
)
{
StringBuilder
sqlString
=
new
StringBuilder
();
// 进行权限过滤,多个角色权限范围之间为或者关系。
List
<
String
>
dataScope
=
Lists
.
newArrayList
();
// 超级管理员,跳过权限过滤
if
(!
user
.
isAdmin
()){
boolean
isDataScopeAll
=
false
;
for
(
Role
r
:
user
.
getRoleList
()){
for
(
String
oa
:
StringUtils
.
split
(
officeAlias
,
","
)){
if
(!
dataScope
.
contains
(
r
.
getDataScope
())
&&
StringUtils
.
isNotBlank
(
oa
)){
if
(
Role
.
DATA_SCOPE_ALL
.
equals
(
r
.
getDataScope
())){
isDataScopeAll
=
true
;
}
else
if
(
Role
.
DATA_SCOPE_COMPANY_AND_CHILD
.
equals
(
r
.
getDataScope
())){
sqlString
.
append
(
" OR "
+
oa
+
".id = '"
+
user
.
getCompany
().
getId
()
+
"'"
);
sqlString
.
append
(
" OR "
+
oa
+
".parent_ids LIKE '"
+
user
.
getCompany
().
getParentIds
()
+
user
.
getCompany
().
getId
()
+
",%'"
);
}
else
if
(
Role
.
DATA_SCOPE_COMPANY
.
equals
(
r
.
getDataScope
())){
sqlString
.
append
(
" OR "
+
oa
+
".id = '"
+
user
.
getCompany
().
getId
()
+
"'"
);
// 包括本公司下的部门 (type=1:公司;type=2:部门)
sqlString
.
append
(
" OR ("
+
oa
+
".parent_id = '"
+
user
.
getCompany
().
getId
()
+
"' AND "
+
oa
+
".type = '2')"
);
}
else
if
(
Role
.
DATA_SCOPE_OFFICE_AND_CHILD
.
equals
(
r
.
getDataScope
())){
sqlString
.
append
(
" OR "
+
oa
+
".id = '"
+
user
.
getOffice
().
getId
()
+
"'"
);
sqlString
.
append
(
" OR "
+
oa
+
".parent_ids LIKE '"
+
user
.
getOffice
().
getParentIds
()
+
user
.
getOffice
().
getId
()
+
",%'"
);
}
else
if
(
Role
.
DATA_SCOPE_OFFICE
.
equals
(
r
.
getDataScope
())){
sqlString
.
append
(
" OR "
+
oa
+
".id = '"
+
user
.
getOffice
().
getId
()
+
"'"
);
}
else
if
(
Role
.
DATA_SCOPE_CUSTOM
.
equals
(
r
.
getDataScope
())){
sqlString
.
append
(
" OR EXISTS (SELECT 1 FROM sys_role_office WHERE role_id = '"
+
r
.
getId
()
+
"'"
);
sqlString
.
append
(
" AND office_id = "
+
oa
+
".id)"
);
}
//else if (Role.DATA_SCOPE_SELF.equals(r.getDataScope())){
dataScope
.
add
(
r
.
getDataScope
());
}
}
}
// 如果没有全部数据权限,并设置了用户别名,则当前权限为本人;如果未设置别名,当前无权限为已植入权限
if
(!
isDataScopeAll
){
if
(
StringUtils
.
isNotBlank
(
userAlias
)){
for
(
String
ua
:
StringUtils
.
split
(
userAlias
,
","
)){
sqlString
.
append
(
" OR "
+
ua
+
".id = '"
+
user
.
getId
()
+
"'"
);
}
}
else
{
for
(
String
oa
:
StringUtils
.
split
(
officeAlias
,
","
)){
//sqlString.append(" OR " + oa + ".id = " + user.getOffice().getId());
sqlString
.
append
(
" OR "
+
oa
+
".id IS NULL"
);
}
}
}
else
{
// 如果包含全部权限,则去掉之前添加的所有条件,并跳出循环。
sqlString
=
new
StringBuilder
();
}
}
if
(
StringUtils
.
isNotBlank
(
sqlString
.
toString
())){
return
" AND ("
+
sqlString
.
substring
(
4
)
+
")"
;
}
return
""
;
}
/**
* 数据范围过滤(符合业务表字段不同的时候使用,采用exists方法)
* @param entity 当前过滤的实体类
* @param sqlMapKey sqlMap的键值,例如设置“dsf”时,调用方法:${sqlMap.sdf}
* @param officeWheres office表条件,组成:部门表字段=业务表的部门字段
* @param userWheres user表条件,组成:用户表字段=业务表的用户字段
* @example
* dataScopeFilter(user, "dsf", "id=a.office_id", "id=a.create_by");
* dataScopeFilter(entity, "dsf", "code=a.jgdm", "no=a.cjr"); // 适应于业务表关联不同字段时使用,如果关联的不是机构id是code。
*/
public
static
void
dataScopeFilter
(
AbstractEntity
<?>
entity
,
String
sqlMapKey
,
String
officeWheres
,
String
userWheres
)
{
User
user
=
entity
.
getCurrentUser
();
// 如果是超级管理员,则不过滤数据
if
(
user
.
isAdmin
())
{
return
;
}
// 数据范围(1:所有数据;2:所在公司及以下数据;3:所在公司数据;4:所在部门及以下数据;5:所在部门数据;8:仅本人数据;9:按明细设置)
StringBuilder
sqlString
=
new
StringBuilder
();
// 获取到最大的数据权限范围
String
roleId
=
""
;
int
dataScopeInteger
=
8
;
for
(
Role
r
:
user
.
getRoleList
()){
int
ds
=
Integer
.
valueOf
(
r
.
getDataScope
());
if
(
ds
==
9
){
roleId
=
r
.
getId
();
dataScopeInteger
=
ds
;
break
;
}
else
if
(
ds
<
dataScopeInteger
){
roleId
=
r
.
getId
();
dataScopeInteger
=
ds
;
}
}
String
dataScopeString
=
String
.
valueOf
(
dataScopeInteger
);
// 生成部门权限SQL语句
for
(
String
where
:
StringUtils
.
split
(
officeWheres
,
","
)){
if
(
Role
.
DATA_SCOPE_COMPANY_AND_CHILD
.
equals
(
dataScopeString
)){
// 包括本公司下的部门 (type=1:公司;type=2:部门)
sqlString
.
append
(
" AND EXISTS (SELECT 1 FROM SYS_OFFICE"
);
sqlString
.
append
(
" WHERE type='2'"
);
sqlString
.
append
(
" AND (id = '"
+
user
.
getCompany
().
getId
()
+
"'"
);
sqlString
.
append
(
" OR parent_ids LIKE '"
+
user
.
getCompany
().
getParentIds
()
+
user
.
getCompany
().
getId
()
+
",%')"
);
sqlString
.
append
(
" AND "
+
where
+
")"
);
}
else
if
(
Role
.
DATA_SCOPE_COMPANY
.
equals
(
dataScopeString
)){
sqlString
.
append
(
" AND EXISTS (SELECT 1 FROM SYS_OFFICE"
);
sqlString
.
append
(
" WHERE type='2'"
);
sqlString
.
append
(
" AND id = '"
+
user
.
getCompany
().
getId
()
+
"'"
);
sqlString
.
append
(
" AND "
+
where
+
")"
);
}
else
if
(
Role
.
DATA_SCOPE_OFFICE_AND_CHILD
.
equals
(
dataScopeString
)){
sqlString
.
append
(
" AND EXISTS (SELECT 1 FROM SYS_OFFICE"
);
sqlString
.
append
(
" WHERE (id = '"
+
user
.
getOffice
().
getId
()
+
"'"
);
sqlString
.
append
(
" OR parent_ids LIKE '"
+
user
.
getOffice
().
getParentIds
()
+
user
.
getOffice
().
getId
()
+
",%')"
);
sqlString
.
append
(
" AND "
+
where
+
")"
);
}
else
if
(
Role
.
DATA_SCOPE_OFFICE
.
equals
(
dataScopeString
)){
sqlString
.
append
(
" AND EXISTS (SELECT 1 FROM SYS_OFFICE"
);
sqlString
.
append
(
" WHERE id = '"
+
user
.
getOffice
().
getId
()
+
"'"
);
sqlString
.
append
(
" AND "
+
where
+
")"
);
}
else
if
(
Role
.
DATA_SCOPE_CUSTOM
.
equals
(
dataScopeString
)){
sqlString
.
append
(
" AND EXISTS (SELECT 1 FROM sys_role_office ro123456, sys_office o123456"
);
sqlString
.
append
(
" WHERE ro123456.office_id = o123456.id"
);
sqlString
.
append
(
" AND ro123456.role_id = '"
+
roleId
+
"'"
);
sqlString
.
append
(
" AND o123456."
+
where
+
")"
);
}
}
// 生成个人权限SQL语句
for
(
String
where
:
StringUtils
.
split
(
userWheres
,
","
)){
if
(
Role
.
DATA_SCOPE_SELF
.
equals
(
dataScopeString
)){
sqlString
.
append
(
" AND EXISTS (SELECT 1 FROM sys_user"
);
sqlString
.
append
(
" WHERE id='"
+
user
.
getId
()
+
"'"
);
sqlString
.
append
(
" AND "
+
where
+
")"
);
}
}
// 设置到自定义SQL对象
entity
.
getSqlMap
().
put
(
sqlMapKey
,
sqlString
.
toString
());
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/service/ICommonService.java
0 → 100644
View file @
d5ba54ba
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.service
;
import
com.jeespring.common.persistence.Page
;
import
org.springframework.transaction.annotation.Transactional
;
import
java.util.List
;
/**
* Service基类
*
* @author HuangBingGui
* @version 2014-05-16
*/
public
interface
ICommonService
<
T
>
{
/**
* 获取单条数据
*
* @param id
* @return
*/
T
get
(
String
id
);
/**
* 获取单条数据
*
* @param entity
* @return
*/
T
get
(
T
entity
);
/**
* 查询列表数据
*
* @param entity
* @return
*/
List
<
T
>
findList
(
T
entity
);
/**
* 查询所有
*
* @param entity
* @return
*/
List
<
T
>
findAllList
(
T
entity
);
/**
* 查询分页数据
*
* @param page 分页对象
* @param entity
* @return
*/
Page
<
T
>
findPage
(
Page
<
T
>
page
,
T
entity
)
;
/**
* 保存数据(插入或更新)
*
* @param entity
*/
@Transactional
(
readOnly
=
false
)
void
save
(
T
entity
)
;
/**
* 删除数据
*
* @param entity
*/
@Transactional
(
readOnly
=
false
)
void
delete
(
T
entity
);
}
JeeSpringCloud/src/main/java/com/jeespring/common/service/InterfaceService.java
0 → 100644
View file @
d5ba54ba
package
com.jeespring.common.service
;
import
com.jeespring.modules.sys.entity.User
;
public
interface
InterfaceService
{
}
Prev
1
2
3
4
5
6
7
8
9
10
…
20
Next
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment