之前一段时间自学了Redis,进行一下总结
三个部分:
1. Linux环境下的redis客户端操作
2. 在java程序中使用redis:
2.1)导入jedis.jar包
2.2)直接 Jedis jedis = new Jedis("192.168.80.131", 6379);获取jedis对象,然后进行操作
2.3)也可以创建jedis连接池JedisPoolUtil,然后需要的时候从连接池中get,使用完release即可
package com.ludada.redis.test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class JedisPoolUtil {
// 被volatile修饰的变量不会被本地线程缓存,对该变量的读写都是直接操作共享内存。
private static volatile JedisPool jedisPool = null;
// 私有化静态方法,不能new
private JedisPoolUtil() {};
//对外提供一个get方法
public static JedisPool getJedisPoolInstance() {
if (jedisPool == null) {
synchronized (JedisPoolUtil.class) {
if (jedisPool == null) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxActive(1000);
poolConfig.setMaxIdle(32);
poolConfig.setMaxWait(100 * 1000);
poolConfig.setTestOnBorrow(true);
jedisPool = new JedisPool(poolConfig, "192.168.80.131",6379);
}
}
}
return jedisPool;
}
//释放回池子
public static void release(JedisPool jedisPool,Jedis jedis){
if(jedis != null){
jedisPool.returnResourceObject(jedis);
}
}
}
3. 然后是spring整合redis,也就是通过redisTemplate对redis进行操作(底层应该也是调用的jedis):
3.1)导入spring-data-redis.jar和jedis.jar
3.2)在spring的配置文件配置redisTemplate
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 连接池配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最大空闲数 -->
<property name="maxIdle" value="50"></property>
<!-- 最大连接数 -->
<property name="maxTotal" value="100"></property>
<!-- 最大等待时间 -->
<property name="maxWaitMillis" value="20000"></property>
</bean>
<!-- 配置连接工厂 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="192.168.80.131"></property>
<property name="port" value="6379"></property>
<!-- <property name="password" value=""></property> -->
<property name="poolConfig" ref="poolConfig"></property>
</bean>
<!-- 配置 key 和 value 的序列化器 -->
<bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
<!-- 配置Redis模板对象 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory"></property>
<property name="keySerializer" ref="stringRedisSerializer"></property>
<property name="valueSerializer" ref="jdkSerializationRedisSerializer"></property>
</bean>
</beans>
3.3)使用redisTemplate
package ldd.Spring_Redis;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
public class myTest {
RedisTemplate redisTemplate = null;
@Before
public void before(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
redisTemplate = ctx.getBean(RedisTemplate.class);
}
@Test
public void Test01() {
Role role = new Role();
role.setId(1L);
role.setNote("note_1");
role.setRoleName("role_name_1");
//存储到到内存中的不是map而是string,进行了序列化
redisTemplate.opsForValue().set("role_1", role);
Role role1 = (Role) redisTemplate.opsForValue().get("role_1");
//上面两步不能保证每次使用RedisTemplate是操作同一个对Redis的连接
System.out.println(role1.toString());
}
@Test
public void Test02(){
final Role role = new Role();
role.setId(1L);
role.setNote("note_1");
role.setRoleName("role_name_1");
SessionCallback callback = new SessionCallback<Role>(){
public Role execute(RedisOperations ops) throws DataAccessException {
ops.boundValueOps("role_1").set(role);
return (Role) ops.boundValueOps("role_1").get();
}
};
Role savedRole = (Role) redisTemplate.execute(callback);
System.out.println(savedRole.getRoleName());
}
}
4.最后便是今天要说的spring缓存整合redis
环境:jdk 1.8 + tomcat 7 + redis 3.0.4 + spring 4.2 + mybatis 3.3.0
先上demo(maven项目):
UserController:
处理器方法
对于数据一致性要求不高的数据,通过redisTemplate进行查找,添加。
对于数据一致性要求较高的数据,直接调用service层方法。
package com.ssm.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.ssm.pojo.User;
import com.ssm.service.IUserService;
/**
* user控制器
*
*/
@Controller
@RequestMapping("/UserCRUD")
public class UserController {
@Resource
private IUserService userService;
@Resource
private RedisTemplate redisTemplate;
/**
* 统计注册用户总数
* @param null
* @return String
* @throws Exception
*/
@RequestMapping("/indexMSG")
public String getIndexMSG(Model model) throws Exception{
String usersCount = null;
//尝试从缓存中取数据
usersCount = (String) redisTemplate.opsForValue().get("users_count");
if(usersCount == null){
//redis缓存中无数据,从数据库中查询,并放入redis缓存中,设置生存时间为1小时
System.out.println("从数据库中取当前已注册用户数量");
usersCount = Integer.toString(userService.selectUsersCount());
redisTemplate.opsForValue().set("users_count", usersCount, 1, TimeUnit.HOURS);
} else {
System.out.println("从redis缓存中取当前已注册用户数量");
}
List<Integer> ids = null;
ids = userService.selectNowIds();
model.addAttribute("usersCount", usersCount);
model.addAttribute("ids", ids);
return "forward:/index.jsp";
}
/**
* 通过ID查询User
*
* @param userId
* @param model
* @return String
*/
@RequestMapping(value = "/getUserById", method = RequestMethod.GET)
public String getUserById(Model model, Integer userId) {
System.out.println("**********getUserById********");
User user = userService.getUserById(userId);
model.addAttribute("user", user); // 填充数据到model
return "showUser";
}
/**
* 查询所有User
*
* @param request
* @param model
* @return
*/
@RequestMapping(value = "/showUser", method = RequestMethod.GET)
public String showUsers(Model model) {
System.out.println("**********showUsers********");
List<User> userList = new ArrayList<User>();
userList = userService.getAllUser();
model.addAttribute("userList", userList); // 填充数据到model
return "showUser";
}
/**
* 增加一个用户
*
* @param userName
* @param sex
* @param age
* @throws Exception
*/
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public void addUser(User user, HttpServletResponse response) throws Exception {
System.out.println("******addUser********");
User result = userService.insertUser(user);
if (result.getId() != 0) {
response.getWriter().print("OK");
} else {
response.getWriter().print("FAIL");
}
}
/**
* 通过userID删除用户
*
* @param userID
* @throws Exception
*/
@RequestMapping(value = "/delUser/{userID}", method = RequestMethod.POST)
public void delUser(@PathVariable int userID, HttpServletResponse response) throws Exception {
System.out.println(userID);
int i = userService.deleteUser(userID);
if(i == 1){
response.getWriter().print("OK");
}else{
response.getWriter().print("删除失败!");
}
}
/**
* 查询用户
*
* @param model
* @param keyWords
* @return
*/
@RequestMapping("/search")
public ModelAndView findUsers(String keyWords) {
System.out.println(keyWords);
ModelAndView mv = new ModelAndView();
List<User> userList = new ArrayList<User>();
userList = userService.findUsers(keyWords);
mv.addObject("userList", userList);
mv.setViewName("showUser");
return mv;
}
/**
* 更新用户信息
* @param userName
* @param sex
* @param age
* @param id
* @return
* @throws Exception
*/
@RequestMapping(value="/editUser",method=RequestMethod.POST)
public void editUser(int id, String name, String sex, int age, HttpServletResponse res) throws Exception {
User user = new User();
user.setId(id);
user.setA