SpringMvc+Maven+Redis
限于服务端返回客户端(java>app) JSON格式返回
这几天一直在研究Redis缓存,查阅了网站各种案列,发现坑太多,导致写这个方法的时候,遇到各种各样的困难。
基本差不多快要放弃了。下面是一个简单的代码。供大家在研究时,参考!
在配置redis之前请把SpringMvc+Maven demo跑起来,如果这个都不行,上网搜索。以下基于框架已经能用的情况下实现的:
在配置Redis的时候,一共遇到2个Redis缓存情况:
1:StringRedisTemplate
2:RedisTemplate
这2种情况详情我也没摸索的太清楚,第一种是存储字符串形式,第二种可以存储集合对象形式。(个人小白见解。)
这2种我都配置好了。但是我还没去做兼容这2个模式,在做出第一种的情况下,返回的格式并不是json格式,或者说返回的格式,无法给客户端去解析,
错误:entity:"[{msg:aaa}]"
正确:entity:[{"msg":"aaa"}]
哪怕我在entity里的toString方法重新 最后还是没有实现成功。导致只能用第二种模式去处理。然而第二种网站的案列坑的你是想跳楼的心都有了。心碎。。。。。。
话不多说 贴上代码:
1:redis.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">
<!-- 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="true" />
</bean>
<!-- redis服务器中心 -->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="poolConfig" />
<property name="port" value="6379" />
<property name="hostName" value="192.168.2.140" />
<property name="password" value="abcdefg123456" />
<property name="timeout" value="-1" />
</bean>
<!-- redisTemplate配置,redisTemplate是对Jedis的对redis操作的扩展,有更多的操作,封装使操作更便捷 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean>
</beans>
此代码可以完全复制,只需要修改你的IP地址和redis密码,如果第一次解压安装redis是没有密码的,需要你去手动设置密码,网上有案列
小坑:需要注意的是redis-server.exe这个是启动服务,你需要把这个服务安装到系统服务里,网上也有,百度下即可很简单
小坑:安装服务时,需要你在cmd命令里面cd到你redis当前文件夹里才可以去安装,别打开redis-cli-exe这个里面安装是没有用的。
2:web.xml
redis.xml配置好后,需要把这个加载到xml里面
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml;classpath:appRedis.xml</param-value>
</context-param>
我的redis.xml是命名 appRedis.xml 你只需要改成你自己xml
这里的spring-mybatis.xml是我自己mysql的配置文件,有的人命名是application.xml自己看着修改。
3:其实到这里就已经配置成功了。这个时候你启动tomcat应该没问题的。
如果出问题:
1:是不是redis ip问题,你的redis config里面的#127.0.0.1也要改成你自己当前电脑的ip地址(我目前还没有配置服务器,仅限本地测试)
2:看看redis.xml里面的ip是否正确,你的密码是否正确。
3:是不是web.xml加载配置文件的时候出问题了。
4:redis服务是不是没有自动启动
其他需要自己百度看看。
下面是怎么去调用该redis缓存。
1:找一个controller类
@Autowired
private RedisTemplate<String, Object> redisTemplate;
然后方法里面写
//存入缓存
redisTemplate.opsForHash().put(table, tableId, value);
//取出缓存
return redisTemplate.opsForHash().get(table, tableId);
这样就可以用了。
然后我自己去封装了一个简单的工具类
----------------------该工具类要放入service层,因为该层已配置注解。如果放入工具层,你会遇到各种各样的坑,网上的坑就是这样来的。
package com.web.pro.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
/**
* redis工具类
* @author Administrator
*/
@Service
public class RedisCacheService{
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 存储集合、单个实体对象
* @param table 表名
* @param tableId 主键ID
* @param value 集合、单个对象
* redisAPI变量名称
* @param table=key
* @param tableId=hashKey
* @param value
*/
public void setObject(String table, String tableId, Object value){
redisTemplate.opsForHash().put(table, tableId, value);
}
/**
* 存储集合、单个实体对象
* @param table 表名
* @param tableId 主键ID
* @param value 集合、单个对象
* redisAPI变量名称
* @param table=key
* @param tableId=hashKey
* @param value
* @return object
*/
public Object getObject(String table, String tableId){
return redisTemplate.opsForHash().get(table, tableId);
}
}
-------------工具类写好后,我们可以在controller里面重新写上面调用的方法
@Autowired
private RedisCacheService cacheService;
注入该工具类方法。
@RequestMapping(value="/testGet",method=RequestMethod.GET)
@ResponseBody
public Map<String,Object> testGet(HttpServletRequest request,HttpServletResponse response){
List<QueueTest> updateResult = null;
Object re = "";
try {
//re = redisTemplate.opsForHash().get("queueTest", "queueId");
re = cacheService.getObject("queueTest", "queueId");
if(com.commons.utils.StringUtils.isObjectNull(re)){
System.out.println("查询一次数据库");
updateResult = queueTestService.getQueueTestAll();
//redisCacheUtil.hset("queueTest", "queueId", "ssss");
//redisTemplate.opsForHash().put("queueTest", "queueId", updateResult);
cacheService.setObject("queueTest", "queueId", updateResult);
}
System.out.println(re);
//SmsSendWorker.pl.setPollinThread(tel,CommonUtils.aa());
//插入集合队列
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LogComm.setLog("IndexController_update(!)"+e.getMessage());
}
return CommonUtils.JSONMethod("20000", "", re);
}
这样浏览器访问的时候就可以了。
其实还要继续优化,应该将存取缓存放入service方法里面去处理。
以上就是我在遇到各种坑的时候,写出来一个小案列,本人小白,勿喷。只想大家在写这个的时候少一点坑。
redis工具类里面还可以继续去优化代码。加入各种存取方法。
Maven:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
如果maven有问题,版本可以查看网上,网上有很多,基本这边是不会出现坑的