下面案例为SpringMVC中使用redis做缓存,案例主要缓存项目中的菜单选项,具体过程为配置缓存池,其他业务类似。对于springBoot中使用Redis可具体参考:我的另外一篇博客,深入实践SpringBoot
一、xml配置
<!-- redis配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最大连接数 -->
<property name="maxActive" value="90" />
<!-- 最大空闲数 -->
<property name="maxIdle" value="5" />
<!-- 最大等待时间 引入jedis实例时等待时间 -->
<property name="maxWait" value="1000" />
<!-- true 表示是否提前验证可用(true) -->
<property name="testOnBorrow" value="true" />
</bean>
<!-- jedisPool -->
<bean id="jedisPool" class=" redis.clients.jedis.JedisPool" destroy-method="destroy">
<constructor-arg ref="jedisPoolConfig" />
<!-- redis服务器ip -->
<constructor-arg value="127.0.0.1" />
<constructor-arg value="6379"/>
</bean>
<!-- redisAPI name对应注入使用的set方法-->
<bean id="redisAPI" class="org.slsale.common.RedisAPI">
<property name="jedisPool" ref="jedisPool"/>
</bean>
二、RedisAPI工具类
package org.slsale.common;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisAPI {
public JedisPool jedisPool;
public JedisPool getJedisPool() {
return jedisPool;
}
public void setJedisPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
/*设置存放redis的key和value值*/
public boolean Set(String key,String value){
Jedis jedis=null;
try{
jedis=jedisPool.getResource();
jedis.set(key, value);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}finally{
returnResource(jedisPool, jedis);
}
}
/*判断key值是否存在*/
public boolean exist(String key){
Jedis jedis=null;
try{
jedis=jedisPool.getResource();
return jedis.exists(key);
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource(jedisPool, jedis);
}
return false;
}
/*返还到数据连接池*/
public static void returnResource(JedisPool pool,Jedis jedis){
if(jedis !=null){
pool.returnResource(jedis);
}
}
/*获取key*/
public String get(String key){
String value =null;
Jedis jedis=null;
try{
jedis=jedisPool.getResource();
value=jedis.get(key);
}catch(Exception e){
e.printStackTrace();
}finally{
returnResource(jedisPool, jedis);
}
return value;
}
}
三、代码调用
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.annotation.InitBinder;
import org.apache.log4j.Logger;
import org.slsale.common.Constants;
import org.slsale.pojo.User;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class BaseController {
Logger logger = Logger.getLogger(BaseController.class);
private User currentUser;//生成对应的set/get方法
//抽取获得当前类的方法
public User getCurrentUser() {
if(null == this.currentUser){
HttpServletRequest request=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
HttpSession session=request.getSession(false);
if(null != session ){
currentUser=(User)session.getAttribute(Constants.SESSION_USER);
}
}
return currentUser;
}
public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
}
/**
* 日期国际化
* */
@InitBinder
public void InitBinder(WebDataBinder databinder){
//表单时间处理
databinder.registerCustomEditor(Date.class, new PropertyEditorSupport(){
public String getAsText() {
return new SimpleDateFormat("yyyy-MM-dd").format((Date)getValue());
}
public void setAsText(String value){
try {
setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
setValue(null);
}
}
});
}
/*@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}*/
}
@Controller
public class AuthorityController extends BaseController {
@Resource
private RedisAPI redisAPI;
//先获取当前用户权限,然后更新操作(redis):将该角色下的所有功能先删除后授权
@RequestMapping(value = "/backend/modifyAuthority.html", produces = {"text/html;charset=UTF-8"})
@ResponseBody
public Object modifyAuthority(HttpSession session,@RequestParam String ids){
String resultString = "nodata";
try {
if(null != ids){
String[] idsArrayString =StringUtils.split(ids,"-");
if(idsArrayString.length > 0){
User user = (User)session.getAttribute(Constants.SESSION_USER);
authorityService.hl_addAuthority(idsArrayString,user.getLoginCode());
//获取主菜单并使用redis API存入
List <Menu> mList = null;
mList = loginController.getFuncByCurrentUser(Integer.valueOf(idsArrayString[0]));
//转换为JSON串
JSONArray jsonArray =JSONArray.fromObject(mList);
redisAPI.Set("menuList"+idsArrayString[0], jsonArray.toString());
//get all role url list to redis
Authority authority = new Authority();
authority.setRoleId(Integer.valueOf(idsArrayString[0]));
List<Function> functionList=functionService.getFunctionListByRoId(authority);
if(null != functionList || functionList.size() >= 0 ){
StringBuffer sBuff=new StringBuffer();
for (Function function : functionList) {
sBuff.append(function.getFuncUrl());
}
redisAPI.Set("Role"+idsArrayString[0]+"UrlList", sBuff.toString());
}
resultString = "success";
}
}
} catch (Exception e) {
e.printStackTrace();
}
return resultString;
}
}
public class SysInterceptor extends HandlerInterceptorAdapter {
private Logger logger = Logger.getLogger(SysInterceptor.class);
//从redis中获取列表加载信息
@Resource
private RedisAPI redisAPI;
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response,
Object handler) throws Exception {
//intercept
HttpSession session = request.getSession();
String urlPath = request.getRequestURI();
User user = ((User)session.getAttribute(Constants.SESSION_USER));
if(null == user){
response.sendRedirect("/");
return false;
}else{
//规则及列表信息与Controller相同
String keyString = "Role"+user.getRoleId() + "UrlList";
String urlsString = "url:"+redisAPI.get(keyString);
if(null != urlsString && !"".equals(urlsString) && urlsString.indexOf(urlPath) > 0){
return true;
}else {
response.sendRedirect("/401.html");
return false;
}
}
}
}