一、在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(非集群)的更多相关文章

  1. springboot2.x版本整合redis(单机/集群)(使用lettuce)

    在springboot1.x系列中,其中使用的是jedis,但是到了springboot2.x其中使用的是Lettuce. 此处springboot2.x,所以使用的是Lettuce.关于jedis跟 ...

  2. springboot整合redis(集群)

    一.加入maven依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId> ...

  3. redis 非集群的主从配置及切换

    单纯的master-slave不能称之为集群,只能叫做读写分离.此案例只针对master为单点服务,且程序端写死master为可写,slave为只读.若master宕机则不可用,若主从未开启持久化,不 ...

  4. Spring Boot 2.x整合Redis

    最近在学习Spring Boot 2.x整合Redis,在这里和大家分享一下,希望对大家有帮助. Redis是什么 Redis 是开源免费高性能的key-value数据库.有以下的优势(源于Redis ...

  5. Spring Boot 2.x 整合 Redis最佳实践

    一.前言 在前面的几篇文章中简单的总结了一下Redis相关的知识.本章主要讲解一下 Spring Boot 2.0 整合 Redis.Jedis 和 Lettuce 是 Java 操作 Redis 的 ...

  6. Redis 一二事 - 在spring中使用jedis 连接调试单机redis以及集群redis

    Redis真是好,其中的键值用起来真心强大啊有木有, 之前的文章讲过搭建了redis集群 那么咋们该如何调用单机版的redis以及集群版的redis来使用缓存服务呢? 先讲讲单机版的,单机版redis ...

  7. Redis Cluster集群搭建后,客户端的连接研究(Spring/Jedis)(待实践)

    说明:无论是否已经搭建好集群,还是使用什么样的客户端去连接,都是必须把全部IP列表集成进去,然后随机往其中一个IP写. 这样做的好处: 1.随机IP写入之后,Redis Cluster代理层会自动根据 ...

  8. spring cloud系列教程第六篇-Eureka集群版

    spring cloud系列教程第六篇-Eureka集群版 本文主要内容: 本文来源:本文由凯哥Java(kaigejava)发布在博客园博客的.转载请注明 1:Eureka执行步骤理解 2:集群原理 ...

  9. Spring Boot WebFlux-06——WebFlux 整合 Redis

    第06课:WebFlux 整合 Redis 前言 上一篇内容讲了如何整合 MongoDB,这里继续讲如何操作 Redis 这个数据源,那什么是 Reids? Redis 是一个高性能的 key-val ...

随机推荐

  1. Flex和Java通信报错

    1.错误描述 11-30 18:15:52 ERROR [localhost-startStop-1] org.springframework.web.servlet.FrameworkServlet ...

  2. pat1121-1131

    1121 #include<cmath> #include<map> #include<iostream> #include<cstring> #inc ...

  3. 如何把Excel中的E+数值批量修改为文本格式?

    日常工作中,经常会出现这样的情况,当我们把一组数据导入EXCEL表中时,本想让数字在表中全部显示出来,但是表格中却以E+的方式显示,如果数据较少,我们可以用最笨的方法一个一个的点击单元格来实现目的,但 ...

  4. 关于C#委托的一些学习笔记

    1.什么是委托就是把方法作为参数传给另一个方法.委托说指向的函数,必须和函数具有相同的签名(返回值和参数类型) Public delegate void DelSayHi(string name); ...

  5. 细说Ajax跨域

    一.什么是跨域 跨域问题来自于浏览器同源策略的限制,包括DOM同源限制和Ajax同源限制,本文探讨的是Ajax跨域.Ajax跨域指的是一个页面的Ajax只能请求和当前页面同源的数据,如果发现请求到的数 ...

  6. beautifulsoup库使用

    介绍与安装 Beautiful Soup 是一个HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 数据.BeautifulSoup 用来解析 HTML 比较简单, API非常人 ...

  7. 【Luogu1291】百事世界杯之旅(动态规划,数学期望)

    [Luogu1291]百事世界杯之旅(动态规划,数学期望) 题面 洛谷 题解 设\(f[i]\)表示已经集齐了\(i\)个名字的期望 现在有两种方法: 先说我自己的: \[f[i]=f[i-1]+1+ ...

  8. MySQL根据出生日期计算年龄的五种方法比较

    方法一 SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(birthday)), '%Y')+0 AS age 方法一,作者也说出了缺陷,就是当日 ...

  9. java volatile关键字解析

    volatile是什么 volatile在java语言中是一个关键字,用于修饰变量.被volatile修饰的变量后,表示这个变量在不同线程中是共享,编译器与运行时都会注意到这个变量是共享的,因此不会对 ...

  10. c#抽取pdf文档标题(2)

    public class IETitle { public static List<WordInfo> WordsInfo = new List<WordInfo>(); pr ...