博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring集成redis
阅读量:5151 次
发布时间:2019-06-13

本文共 19291 字,大约阅读时间需要 64 分钟。

redis是一种非关系型数据库,与mongoDB不同的是redis是内存数据库,所以访问速度很快。常用作缓存和发布-订阅式的消息队列。redis官方没有提供windows版本的软件。windows版本一直是微软维护的。

下载地址

这里是redis相关的教程。

在spring中集成redis很简单,这里用的是ssm框架+maven构建的项目。

首先是需要引入的pom.xml文件:

4.0.0
SSMRedisDemo
SSMRedisDemo
war
0.0.1-SNAPSHOT
SSMRedisDemo Maven Webapp
http://maven.apache.org
UTF-8
4.2.0.RELEASE
org.springframework
spring-context
${spring.version}
org.springframework
spring-aop
${spring.version}
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-web
${spring.version}
javax.servlet
jstl
1.2
commons-logging
commons-logging
1.1.3
org.codehaus.jackson
jackson-mapper-asl
1.9.13
com.fasterxml.jackson.core
jackson-annotations
2.6.1
com.fasterxml.jackson.core
jackson-core
2.6.1
com.fasterxml.jackson.core
jackson-databind
2.6.1
org.springframework
spring-orm
${spring.version}
org.mybatis
mybatis-spring
1.2.3
mysql
mysql-connector-java
5.1.36
org.mybatis
mybatis
3.3.0
c3p0
c3p0
0.9.1.2
org.slf4j
slf4j-log4j12
1.7.12
log4j
log4j
1.2.17
org.springframework.data
spring-data-redis
1.6.0.RELEASE
redis.clients
jedis
2.7.3
maven-compiler-plugin
3.1
1.7
1.7
maven-war-plugin
2.4
WebContent
false

项目基本架构:

jdbc.properties:

jdbc.host=127.0.0.1jdbc.database=userjdbc.port=3306jdbc.username=rootjdbc.password=root

 log4j.properties:

# Global logging configurationlog4j.rootLogger=WARN,stdout# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n# mybatis loglog4j.logger.com.ssm.dao.UserMapper=DEBUG# lyz loglog4j.logger.com.ssm.controller=DEBUGlog4j.logger.com.ssm.service=DEBUG

 

redis.porperties:

# Redis settings  redis.host=127.0.0.1redis.port=6379  #redis.pass=passwordredis.dbIndex=0  redis.expiration=3000  redis.maxIdle=300  redis.maxActive=600  redis.maxWait=1000  redis.testOnBorrow=true

 

applicationContext.xml:

classpath:jdbc.properties
classpath:redis.properties

 

springmvc.xml:

application/json;charset=UTF-8

 

web.xml:

Archetype Created Web Application
/index.jsp
contextConfigLocation
classpath:spring/applicationContext.xml
org.springframework.web.context.ContextLoaderListener
springfilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
springfilter
/*
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring/springmvc.xml
1
true
SpringMVC
/

 

UserController:

package com.ssm.controller;import java.util.ArrayList;import java.util.List;import javax.annotation.Resource;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控制器 *  * @author YaoQi */@Controller@RequestMapping("/UserCRUD")public class UserController {    @Resource    private IUserService userService;    /**     * 查询所有User     *      * @param request     * @param model     * @return     */    @RequestMapping(value = "/showUser", method = RequestMethod.GET)    public String showUsers(Model model) {        System.out.println("**********showUsers********");        List
userList = new ArrayList
(); userList = userService.getAllUser(); model.addAttribute("userList", userList); // 填充数据到model return "showUser"; } /** * 增加一个用户 * * @param userName * @param sex * @param age * @return */ @RequestMapping(value = "/addUser", method = RequestMethod.POST) @ResponseBody public ModelMap addUser(String userName, String sex, int age) { System.out.println("******addUser********"); System.out.println(userName + sex + age); User user = new User(); user.setsex(sex); user.setUserName(userName); user.setAge(age); userService.insertUser(user); ModelMap model = new ModelMap(); model.addAttribute("result", "添加成功"); return model; } /** * 通过userID删除用户 * * @param userID */ @RequestMapping(value = "/delUser/{userID}", method = RequestMethod.GET) public ModelAndView delUser(@PathVariable int userID) { System.out.println(userID); userService.deleteUser(userID); ModelAndView mv = new ModelAndView(); List
userList = new ArrayList
(); userList = userService.getAllUser(); mv.addObject("userList", userList); // 填充数据到model mv.setViewName("showUser"); return mv; } /** * 查询用户 * * @param model * @param keyWords * @return */ @RequestMapping(value = "/search", method = RequestMethod.POST) public String findUsers(Model model, String keyWords) { System.out.println(keyWords); List
userList = new ArrayList
(); userList = userService.findUsers(keyWords); model.addAttribute("userList", userList); // 填充数据到model return "showUser"; } /** * 更新用户信息 * @param userName * @param sex * @param age * @param id * @return */ @RequestMapping(value="/editUser",method=RequestMethod.POST) public ModelAndView editUser(String userName, String sex, int age, int id) { System.out.println(userName + sex + age); User user = new User(); user.setsex(sex); user.setUserName(userName); user.setAge(age); user.setId(id); userService.editUser(user); ModelAndView mv = new ModelAndView(); List
userList = new ArrayList
(); userList = userService.getAllUser(); mv.addObject("userList", userList); // 填充数据到model mv.setViewName("redirect:/UserCRUD/showUser"); return mv; }}

 

User:

package com.ssm.pojo;import java.io.Serializable;/** * User实体类对应数据库中的tb_user表 *  * @author YaoQi * 要想使用redis存对象,一定要让实体类实现Serializable接口,否则会报错。 */public class User implements Serializable{    /**     *      */    private static final long serialVersionUID = -5244288298702801619L;    private int id;    private String userName;    private String sex;    private int age;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getsex() {        return sex;    }    public void setsex(String sex) {        this.sex = sex;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    @Override    public String toString() {        return "User [id=" + id + ", userName=" + userName + ", sex=" + sex + ", age=" + age + "]";    }}

 

UserMapper:

package com.ssm.dao;import java.util.List;import com.ssm.pojo.User;public interface UserMapper {    public User selectByPrimaryKey(int userId);    public List
selectAllUser(); public void insertUser(User user); public void deleteUser(int id); public List
findUsers(String keyWords); public void editUser(User user);}

 

UserMapper.xml: 与对应的接口放到同一包下面。

id,userName,sex,age
INSERT INTO tb_user(userName,sex,age) VALUES (#{userName},#{sex},#{age})
DELETE FROM tb_user WHERE id=#{id}
UPDATE tb_user SET userName=#{userName}, sex=#{sex},age=#{age} WHERE id=#{id}

 

IUserService:

package com.ssm.service;import java.util.List;import com.ssm.pojo.User;/** * user表的操作接口 * @author YaoQi */public interface IUserService {    /**     * 通过id查询user接口方法     * @param userId     * @return     */     public User getUserById(int userId);            /**      * 查询所有的user      * @return 返回userList      */     public List
getAllUser(); /** * 添加一个user * @param user */ public void insertUser(User user); /** * 通过ID删除用户 * @param id */ public void deleteUser(int id); /** * 通过关键字查询用户 * @param keyWords * @return */ public List
findUsers(String keyWords); /** * 更新用户 * @param user */ public void editUser(User user);}

 

ServiceImple:

package com.ssm.serviceImpl;import java.util.List;import javax.annotation.Resource;import org.springframework.cache.annotation.CacheEvict;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;import com.ssm.dao.UserMapper;import com.ssm.pojo.User;import com.ssm.service.IUserService;/** * userService *  * 缓存机制说明:所有的查询结果都放进了缓存,也就是把MySQL查询的结果放到了redis中去, * 然后第二次发起该条查询时就可以从redis中去读取查询的结果,从而不与MySQL交互,从而达到优化的效果, * redis的查询速度之于MySQL的查询速度相当于 内存读写速度 /硬盘读写速度  * @Cacheable("a")注解的意义就是把该方法的查询结果放到redis中去,下一次再发起查询就去redis中去取,存在redis中的数据的key就是a; * @CacheEvict(value={"a","b"},allEntries=true) 的意思就是执行该方法后要清除redis中key名称为a,b的数据; */@Service("userService")@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)  public class UserServiceImpl implements IUserService {    @Resource    private UserMapper iUserDao;    @Cacheable("getUserById") //标注该方法查询的结果进入缓存,再次访问时直接读取缓存中的数据    @Override    public User getUserById(int userId) {        return this.iUserDao.selectByPrimaryKey(userId);    }    @Cacheable("getAllUser")    @Override    public List
getAllUser() { return this.iUserDao.selectAllUser(); } @CacheEvict(value= {"getAllUser","getUserById","findUsers"},allEntries=true)//清空缓存,allEntries变量表示所有对象的缓存都清除 @Override public void insertUser(User user) { this.iUserDao.insertUser(user); } @CacheEvict(value= {"getAllUser","getUserById","findUsers"},allEntries=true) @Override public void deleteUser(int id) { this.iUserDao.deleteUser(id); } @Cacheable("findUsers") @Override public List
findUsers(String keyWords) { return iUserDao.findUsers(keyWords); } @CacheEvict(value= {"getAllUser","getUserById","findUsers"},allEntries=true) @Override public void editUser(User user) { this.iUserDao.editUser(user); }}

 缓存主要在service层进行,查询的结果会缓存,把对象序列号存到redis中去,key就是注解中的参数,例如@Cacheable("findUsers"): 存在redis中的key就是findUsers。缓存了这个结果之后再次请求这个方法就不会去数据库中查,而是从redis缓存中读取数据,这样就减少了跟数据库之间的交互。然后修改、删除、增加操作就会清除缓存,保持数据的一致性。

 

RedisCacheConfig: 需要增加这个配置类,会在applicationContex配置文件中注册这个bean。

package com.ssm.utils;import java.lang.reflect.Method;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.annotation.EnableCaching;import org.springframework.cache.interceptor.KeyGenerator;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;/** * 通过spring管理redis缓存配置 *  * @author Administrator * */@Configuration  @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport {    private volatile JedisConnectionFactory jedisConnectionFactory;    private volatile RedisTemplate
redisTemplate; private volatile RedisCacheManager redisCacheManager; public RedisCacheConfig() { super(); } /** * 带参数的构造方法 初始化所有的成员变量 * * @param jedisConnectionFactory * @param redisTemplate * @param redisCacheManager */ public RedisCacheConfig(JedisConnectionFactory jedisConnectionFactory, RedisTemplate
redisTemplate, RedisCacheManager redisCacheManager) { this.jedisConnectionFactory = jedisConnectionFactory; this.redisTemplate = redisTemplate; this.redisCacheManager = redisCacheManager; } public JedisConnectionFactory getJedisConnecionFactory() { return jedisConnectionFactory; } public RedisTemplate
getRedisTemplate() { return redisTemplate; } public RedisCacheManager getRedisCacheManager() { return redisCacheManager; } @Bean public KeyGenerator customKeyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... objects) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : objects) { sb.append(obj.toString()); } return sb.toString(); } }; }}

转载于:https://www.cnblogs.com/youqc/p/8589174.html

你可能感兴趣的文章
14.匿名函数和闭包
查看>>
ceph 手工部署
查看>>
git上传项目全部流程
查看>>
非官方翻译《如何在 Vitamio 中使用自己编译的 FFmpeg?》
查看>>
Linux搜索文件、文件夹数、文件个数命令
查看>>
MySQL Err(1024):Lock wait timeout exceeded; try restarting transaction
查看>>
Voide标签
查看>>
emacs使用笔记
查看>>
ETL
查看>>
opencv图像腐蚀代码
查看>>
Java 网络IO编程(BIO、NIO、AIO)
查看>>
20141013--判断语句(if ,else)
查看>>
机械硬盘拒绝访问找回数据的办法
查看>>
ARM-Linux移植之二
查看>>
mono for android 读取网络远程图片
查看>>
mysql xtrabackup 备份恢复实现,mysql命令备份数据库,打包压缩数据库
查看>>
技术要点总结(2):IO流
查看>>
第四次作业
查看>>
mysql 基础语句
查看>>
【翻译】Sencha Cmd中脚本压缩方法之比较
查看>>