一、在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. 硬盘运行与“AHCI 模式”还是“IDE 模式”

    如今SATA硬盘越来越流行,最新购买或者组装的电脑,基本都安装新一代的SATA硬盘,由于绝大多数BIOS初始设置是"IDE模式",安装的windows XP和vista系统,并没有 ...

  2. ONCOCNV软件思路分析之tumor处理

    前期处理 perl脚本统计RC(RC(read counts)) 读入control baseline 和 sigma(最后baseline 预测的mad值) 将gc < 0.28或gc > ...

  3. 一个完整的springmvc + ajaxfileupload实现图片异步上传的案例

    一,原理 详细原理请看这篇文章 springmvc + ajaxfileupload解决ajax不能异步上传图片的问题.java.lang.ClassCastException: org.apache ...

  4. 4-20mA 意义

    工业上最广泛采用的标准模拟量电信号是用4~20mA直流电流来传输模拟量. 采用电流信号的原因是不容易受干扰.并且电流源内阻无穷大,导线电阻串联在回路中不影响精度,在普通双绞线上可以传输数百米.上限取2 ...

  5. java的几种引用之二

    import java.lang.ref.PhantomReference;import java.lang.ref.ReferenceQueue;import java.lang.ref.SoftR ...

  6. JS中ptototype和__proto__的关系

    学到原型的时候感觉头都大了/(ㄒoㄒ)/~~ 尤其是ptototype和__proto__ 傻傻分不清  通过多番查找资料,根据自己的理解,总结如下: 一.构造函数: 构造函数:通过new关键字可以用 ...

  7. C# Hook原理及EasyHook简易教程

    前言 在说C# Hook之前,我们先来说说什么是Hook技术.相信大家都接触过外挂,不管是修改游戏客户端的也好,盗取密码的也罢,它们都是如何实现的呢? 实际上,Windows平台是基于事件驱动机制的, ...

  8. [APIO2009]会议中心

    [APIO2009]会议中心 题目大意: 原网址与样例戳我! 给定n个区间,询问以下问题: 1.最多能够选择多少个不相交的区间? 2.在第一问的基础上,输出字典序最小的方案. 数据范围:\(n \le ...

  9. [HNOI2015]亚瑟王

    题面在这里 题意 \(n\)张卡按照一定顺序排列,每轮从第\(1\)张开始考虑到最后一张,考虑一张卡时有\(p[i]\)的概率产生\(d[i]\)的贡献,产生贡献时直接退出该轮并在之后的考虑中直接跳过 ...

  10. [BZOJ2733] [HNOI2012] 永无乡 (splay启发式合并)

    Description 永无乡包含 n 座岛,编号从 1 到 n,每座岛都有自己的独一无二的重要度,按照重要度可 以将这 n 座岛排名,名次用 1 到 n 来表示.某些岛之间由巨大的桥连接,通过桥可以 ...