【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(非集群)的更多相关文章
- springboot2.x版本整合redis(单机/集群)(使用lettuce)
在springboot1.x系列中,其中使用的是jedis,但是到了springboot2.x其中使用的是Lettuce. 此处springboot2.x,所以使用的是Lettuce.关于jedis跟 ...
- springboot整合redis(集群)
一.加入maven依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId> ...
- redis 非集群的主从配置及切换
单纯的master-slave不能称之为集群,只能叫做读写分离.此案例只针对master为单点服务,且程序端写死master为可写,slave为只读.若master宕机则不可用,若主从未开启持久化,不 ...
- Spring Boot 2.x整合Redis
最近在学习Spring Boot 2.x整合Redis,在这里和大家分享一下,希望对大家有帮助. Redis是什么 Redis 是开源免费高性能的key-value数据库.有以下的优势(源于Redis ...
- Spring Boot 2.x 整合 Redis最佳实践
一.前言 在前面的几篇文章中简单的总结了一下Redis相关的知识.本章主要讲解一下 Spring Boot 2.0 整合 Redis.Jedis 和 Lettuce 是 Java 操作 Redis 的 ...
- Redis 一二事 - 在spring中使用jedis 连接调试单机redis以及集群redis
Redis真是好,其中的键值用起来真心强大啊有木有, 之前的文章讲过搭建了redis集群 那么咋们该如何调用单机版的redis以及集群版的redis来使用缓存服务呢? 先讲讲单机版的,单机版redis ...
- Redis Cluster集群搭建后,客户端的连接研究(Spring/Jedis)(待实践)
说明:无论是否已经搭建好集群,还是使用什么样的客户端去连接,都是必须把全部IP列表集成进去,然后随机往其中一个IP写. 这样做的好处: 1.随机IP写入之后,Redis Cluster代理层会自动根据 ...
- spring cloud系列教程第六篇-Eureka集群版
spring cloud系列教程第六篇-Eureka集群版 本文主要内容: 本文来源:本文由凯哥Java(kaigejava)发布在博客园博客的.转载请注明 1:Eureka执行步骤理解 2:集群原理 ...
- Spring Boot WebFlux-06——WebFlux 整合 Redis
第06课:WebFlux 整合 Redis 前言 上一篇内容讲了如何整合 MongoDB,这里继续讲如何操作 Redis 这个数据源,那什么是 Reids? Redis 是一个高性能的 key-val ...
随机推荐
- Errors running buider 'DeploymentBuilder' on project 'HFMS'
1.错误描述 2.错误原因 HFMS项目不是利用MyEclipse创建的,但是用MyEclipse打开的 3.解决办法 (1)关闭MyEclipse,找到HFMS项目,删除"com.genu ...
- 创建数据库表默认字段封装SQL
declare @Table_Name varchar(500) declare @strSQL varchar(500) set @Table_Name='UserInfo' --在此处设置要创建的 ...
- 小白学爬虫-批量部署Splash负载集群
整体目录如下: study@study:~/文档/ansible-examples$ tree Splash_Load_balancing_cluster Splash_Load_balancing_ ...
- iOS - XMPP 的使用
1.XMPP XMPP 是一个基于 Socket 通信的即时通讯的协议,它规范了即时通信在网络上数据的传输格式,比如登录,获取好友列表等等的格式.XMPP 在网络传输的数据是 XML 格式. 开发架构 ...
- CentOS7.2编译安装PHP7.2.3之史上最详细步骤。
首先,我们的CentOS版本信息如下: 开始我们的编译. 第一步: 将php安装包安装到/usr/src目录下. cd /usr/src && wget http://cn2.php. ...
- C#图解教程 第十八章 枚举器和迭代器
枚举器和迭代器 枚举器和可枚举类型 foreach语句 IEnumerator接口 使用IEnumerable和IEnumerator的示例 泛型枚举接口迭代器 迭代器块使用迭代器来创建枚举器使用迭代 ...
- 【BZOJ3675】序列分割(斜率优化,动态规划)
[BZOJ3675]序列分割(斜率优化,动态规划) 题面 Description 小H最近迷上了一个分隔序列的游戏.在这个游戏里,小H需要将一个长度为n的非负整数序列分割成k+1个非空的子序列.为了得 ...
- Spring入门看这一篇就够了
前言 前面已经学习了Struts2和Hibernate框架了.接下来学习的是Spring框架...本博文主要是引入Spring框架... Spring介绍 Spring诞生: 创建Spring的目的就 ...
- shell 脚本下执行Mongodb命令
最近项目中搭建了两台mongodb的服务器,由于服务器只有两台的情况下,目前只是搭建了主从模式架构(官方目前并不推荐主从模式),缺点就是故障转移不变等等原因,而是推荐副本集模式(这里就不多说了)... ...
- 用Tortoisegit往GitHub上push时,失败并显示git did not exit cleanly (exit code 1),可能是GitHub的Email的原因
之前我看到错误,总是没有耐心地读完整个错误,而是不假思索地搜索一部分错误,导致偏离正确轨道,相当于号错脉了,比如这里只是搜索git did not exit cleanly (exit code 1) ...