【Spring系列】Spring mvc整合redis(非集群)

一、在pom.xml中增加redis需要的jar包

 <!--spring redis相关jar包-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.9.RELEASE</version>
</dependency>

二、准备redis.properties文件,位置在resources文件夹下

redis.host=192.168.181.201
redis.port=6379
redis.pass=123456
redis.timeout=-1
redis.maxIdle=100
redis.minIdle=8
redis.maxWait=-1
redis.testOnBorrow=true

三、在applicationContext.xml中增加集成redis的配置

<!--集成redis-->
<!--jedis配置-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="100"/>
<property name="minIdle" value="8"/>
<property name="maxWaitMillis" value="-1"/>
<property name="testOnBorrow" value="false"/>
</bean>
<!--redis服务器中心-->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="poolConfig"/>
<property name="port" value="6379"/>
<property name="hostName" value="192.168.181.201"/>
<property name="password" value="123456"/>
<property name="timeout" value="-1"/>
</bean>
<!--redis操作模板 面向对象的模板-->
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<!--如果不配置Serializer 那么存储的时候只能使用String ,如果用对象类型存储,那么会提示错误-->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean>

  

四、编写redis操作工具类

package com.slp.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component; import javax.annotation.Resource; /**
* @author sanglp
* @create 2018-01-31 9:08
* @desc 操作hash的工具类
**/
@Component("redisCache")
public class RedisCacheUtil {
@Resource
private StringRedisTemplate redisTemplate; /**
* 向Hash中添加值
* @param key 可以对应数据库中的表名
* @param field 可以对应数据库表中的唯一索引
* @param value 存入redis中的值
*/
public void hset(String key,String field,String value){
if (key == null || "".equals(key)){
return;
}
redisTemplate.opsForHash().put(key,field,value);
} /**
* 从redis中取出值
* @param key
* @param field
* @return
*/
public String hget(String key,String field){
if (key == null || "".equals(key)){
return null;
}
return (String)redisTemplate.opsForHash().get(key,field);
} /**
* 查询key中对应多少条数据
* @param key
* @param field
* @return
*/
public boolean hexists(String key,String field){
if(key == null|| "".equals(key)){
return false;
}
return redisTemplate.opsForHash().hasKey(key,field);
} /**
* 删除
* @param key
* @param field
*/
public void hdel(String key,String field){
if(key == null || "".equals(key)){
return;
}
redisTemplate.opsForHash().delete(key,field);
}
}

  

五、使用junit进行测试

package com.slp;

import com.slp.util.RedisCacheUtil;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext; /**
* @author sanglp
* @create 2018-01-31 9:16
* @desc redis测试类
**/
public class RedisTest {
private RedisCacheUtil redisCache;
private static String key;
private static String field;
private static String value; @Before
public void setUp() throws Exception {
//ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("D:/web-back/web-back/myweb/web/WEB-INF/applicationContext.xml");
//context.start(); String path="web/WEB-INF/applicationContext.xml";
ApplicationContext context = new FileSystemXmlApplicationContext(path);
redisCache = (RedisCacheUtil) context.getBean("redisCache");
} // 初始化 数据
static {
key = "tb_student";
field = "stu_name";
value = "一系列的关于student的信息!";
} // 测试增加数据
@Test
public void testHset() {
redisCache.hset(key, field, value);
System.out.println("数据保存成功!");
} // 测试查询数据
@Test
public void testHget() {
String re = redisCache.hget(key, field);
System.out.println("得到的数据:" + re);
} // 测试数据的数量
@Test
public void testHsize() {
//long size = redisCache.hsize(key);
// System.out.println("数量为:" + size);
}
}

六、在项目中简单使用  

package com.slp.web;

import com.slp.dto.UserInfo;
import com.slp.service.UserInfoService;
import com.slp.util.EHCacheUtil;
import com.slp.util.RedisCacheUtil;
import net.sf.ehcache.CacheManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest;
import java.util.List; /**
* @author sanglp
* @create 2018-01-23 9:04
* @desc 登陆入口
**/
@Controller
public class LoginController {
private Logger logger= Logger.getLogger(this.getClass());
@Autowired
private UserInfoService userInfoService;
@Autowired
private CacheManager cacheManager;
@Autowired
private RedisCacheUtil redisCacheUtil;
/**
* 进入登陆首页页面
* @param map
* @return
*/
@RequestMapping(value = "login",method = {RequestMethod.POST,RequestMethod.GET})
public String login(ModelMap map){
//进入登陆页面
return "login"; } /**
* 获取用户信息监测是否已注册可以登录
* @param map
* @param request
* @return
*/
@RequestMapping(value = "loginConfirm",method = {RequestMethod.POST,RequestMethod.GET})
public String loginConfirm(ModelMap map, HttpServletRequest request){
EHCacheUtil.put("FirstKey",request.getParameter("email") );
//登陆提交页面
String email = request.getParameter("email");
logger.info("email="+email);
String password = request.getParameter("password");
logger.info("password="+password);
UserInfo userInfo = new UserInfo();
userInfo.setEmail(email);
userInfo.setUserPassword(password);
UserInfo user= userInfoService.selectUserByEmail(userInfo);
String userEmail = redisCacheUtil.hget("userInfo","email");
logger.debug("userEmail in redis cache is = "+userEmail);
if(null == userEmail){
redisCacheUtil.hset("userInfo","email",email);
}
if (user==null){
return "signUp";
}
List keys = EHCacheUtil.getKeys();
for(int i=0;i<keys.size();i++){
logger.debug(keys.get(i));
logger.debug(EHCacheUtil.get(keys.get(i)));
}
logger.info(user.getEmail());
logger.info(user.getId());
if(!user.getUserPassword().equals(password)){
map.addAttribute("msg","请输入正确的密码");
return "login";
}else {
request.getSession().setAttribute("email",user.getEmail());
request.getSession().setAttribute("userName",user.getUserName());
request.getSession().setAttribute("userId",user.getId());
logger.info("校验通过");
return "index";
} }
}

日志截图:

 【Spring系列】Spring mvc整合redis(非集群)

【Spring系列】Spring mvc整合redis(非集群)  

上一篇:转:【Java集合源码剖析】Vector源码剖析


下一篇:.NET Core的文件系统[3]:由PhysicalFileProvider构建的物理文件系统