Spring与Mybatis基于注解整合Redis的方法

网友投稿 216 2023-07-06


Spring与Mybatis基于注解整合Redis的方法

基于这段时间折腾redis遇到了各种问题,想着整理一下。本文主要介绍基于Spring+Mybatis以注解的形式整合Redis。废话少说,进入正题。

首先准备Redis,我下的是Windows版,下载后直接启动redis-server就行了,见下图:

一,先上jar包

二,创建实体类

package com.sl.user.vo;

import java.io.Serializable;

import com.fasterxml.jackson.databind.PropertyNamingStrategy;

import com.fasterxml.jackson.databind.annotation.jsonNaming;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

@JsonSerialize

@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)

public class UserVO implements Serializable{

private static final long serialVersionUID = 1L;

private int id;

private String username;

private String password;

private int age;

public UserVO(){

super();

}

public UserVO(int id, String username, String password, int age) {

super();

this.id = id;

this.username = username;

this.password = password;

this.age = 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 getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

@Override

public String toString() {

return "UserVO [id=" + id + ", username=" + username + ", password="

+ password + ", age=" + age + "]";

}

}

三,dao接口

package com.sl.user.dao;

import com.sl.user.vo.UserVO;

public interface UserDao {

public void addUser(UserVO user);

public void deleteUser(UserVO user);

public void updateUser(UserVO user);

public UserVO getUserById(int id);

public UserVO getUser(int id);

}

四,UserMapper

insert into t_user(username,password,age) values(#{username},#{password},#{age})

delete * from t_user where id = #{id}

update t_user set

username = #{username},

password = #{password},

age = #{age}

where 1=1

and id = #{id}

select * from t_user where id = #{id}

select username from t_user where id = #{id}

五,Service接口

package com.sl.user.service;

import com.sl.user.vo.UserVO;

public interface UserService {

public void addUser(UserVO user);

public void deleteUser(UserVO user);

public void updateUser(UserVO user);

public UserVO getUserById(int id);

public UserVO getUser(int id);

}

六,Service实现

package com.sl.user.service.impl;

import org.springframework.beans.factory.annotation.Autowired;

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.sl.user.dao.UserDao;

import com.sl.user.service.UserService;

import com.sl.user.vo.UserVO;

@Service("userService")

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)

public class UserServiceImpl implements UserService{

@Autowired

private UserDao userDao;

@Override

@CacheEvict(value="User",key="addUser",allEntries=true)

public void addUser(UserVO user) {

userDao.addUser(user);

}

@Override

@CacheEvict(value = {"getUser", "getUserById"}, allEntries = true)

public void deleteUser(UserVO user) {

userDao.deleteUser(user);

}

@Override

@CacheEvict(value = {"getUser", "getUserById"}, allEntries = true)

public void updateUser(UserVO user) {

userDao.updateUser(user);

}

@Override

@Cacheable(value="User",key="gehttp://tUserById")

public UserVO getUserById(int id) {

return userDao.getUserById(id);

}

@Override

@Cacheable(value="User",key="'getUser'")

public UserVO getUser(int id) {

return userDao.getUser(id);

}

}

七,Ctrl层

package com.sl.user.web;

import java.util.HashMap;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import com.sl.user.service.UserService;

import com.sl.user.vo.UserVO;

@Controller

@RequestMapping("/userCtrl")

public class UserCtrl {

@Autowired

private UserService userService;

@RequestMapping("/addUser")

public void addUser(UserVO user){

userService.addUser(user);

}

@RequestMapping("/deleteUser")

public void deleteUser(UserVO user){

userService.deleteUser(user);

}

@RequestMapping("/updateUser")

public void updateUser(UserVO user){

userService.updateUser(user);

}

@ResponseBody

@RequestMapping("/getUserById")

public Map getUserById(UserVO user){

Map map = new HashMap();

map.put("msg",userService.getUserById(4));

return map;

}

@ResponseBody

@RequestMapping("/getUser")

public Map getUser(UserVO vo){

Map map = new HashMap();

Object user = userService.getUser(4);

map.put("msg",user.toString());

return map;

}

}

八,Redis关键类,用于CRUD操作

package com.sl.user.redis;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import org.springframework.cache.Cache;

import org.springframework.cache.support.SimpleValueWrapper;

import org.springframework.dao.DataAccessException;

import org.springframework.data.redis.connection.RedisConnection;

import org.springframework.data.redis.core.RedisCallback;

import org.springframework.data.redis.core.RedisTemplate;

public class RedisUtil implements Cache{

private RedisTemplate redisTemplate;

private String name;

public RedisTemplate getRedisTemplate() {

return redisTemplate;

}

public void setRedisTemplate(RedisTemplate redisTemplate) {

this.redisTemplate = redisTemplate;

}

public void setName(String name) {

this.name = name;

}

@Override

public String getName() {

return this.name;

}

@Override

public Object getNativeCache() {

return this.redisTemplate;

}

/**

* 从缓存中获取key

*/

@Override

public ValueWrapper get(Object key) {

System.out.println("get key");

final String keyf = key.toString();

Object object = null;

object = redisTemplate.execute(new RedisCallback() {

public Object doInRedis(RedisConnection connection)

throws DataAccessException {

byte[] key = keyf.getBytes();

byte[] value = connection.get(key);

if (value == null) {

return null;

}

return toObject(value);

}

});

return (object != null ? new SimpleValueWrapper(object) : null);

}

/**

* 将一个新的key保存到缓存中

* 先拿到需要缓存key名称和对象,然后将其转成ByteArray

*/

@Override

public void put(Object key, Object value) {

System.out.println("put key");

final String keyf = key.toString();

final Object valuef = value;

final long liveTime = 86400;

redisTemplate.execute(new RedisCallback() {

public Long doInRedis(RedisConnection connection)

throws DataAccessException {

byte[] keyb = keyf.getBytes();

byte[] valueb = toByteArray(valuef);

connection.set(keyb, valueb);

if (liveTime > 0) {

connection.expire(keyb, liveTime);

}

return 1L;

}

});

}

private byte[] toByteArray(Object obj) {

byte[] bytes = null;

ByteArrayOutputStream bos = new ByteArrayOutputStream();

try {

ObjectOutputStream oos = new ObjectOutputStream(bos);

oos.writeObject(obj);

oos.flush();

bytes = bos.toByteArray();

oos.close();

bos.close();

}catch (IOException ex) {

ex.printStackTrace();

}

return bytes;

}

private Object toObject(byte[] bytes) {

Object obj = null;

try {

ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

ObjectInputStream ois = new ObjectInputStream(bis);

obj = ois.readObject();

ois.close();

bis.close();

} catch (IOException ex) {

ex.printStackTrace();

} catch (ClassNotFoundException ex) {

ex.printStackTrace();

}

return obj;

}

/**

* 删除key

*/

@Override

public void evict(Object key) {

System.out.println("del key");

final String keyf = key.toString();

redisTemplate.execute(new RedisCallback() {

public Long doInRedis(RedisConnection connection)

throws DataAccessException {

return connection.del(keyf.getBytes());

}

});

}

/**

* 清空key

*/

@Override

public void clear() {

System.out.println("clear key");

redisTemplate.execute(new RedisCallback() {

public String doInRedis(RedisConnection connection)

throws DataAccessException {

connection.flushDb();

return "ok";

}

});

}

@Override

public T get(Object key, Class type) {

return null;

}

@Override

public ValueWrapper putIfAbsent(Object key, Object value) {

return null;

}

}

九,Spring整合mybatis和redis配置文件

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:p="http://springframework.org/schema/p"

xmlns:context="http://springframework.org/schema/context"

xmlns:tx="http://springframework.org/schema/tx"

xmlns:mvc="http://springframework.org/schema/mvc"

xmlns:aop="http://springframework.org/schema/aop"

xmlns:cache="http://springframework.org/schema/cache"

xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans-4.0.xsd

http://springframework.org/schema/aop http://springframework.org/schema/aop/spring-aop-4.0.xsd

http://springframework.org/schema/tx http://springframework.org/schema/tx/spring-tx-4.0.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context-4.0.xsd

http://springframework.org/schema/mvc http://springframework.org/schema/mvc/spring-mvc-4.0.xsd

http://springframework.org/schema/cache http://springframework.org/schema/cache/spring-cache.xsd">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:p="http://springframework.org/schema/p"

xmlns:context="http://springframework.org/schema/context"

xmlns:tx="http://springframework.org/schema/tx"

xmlns:mvc="http://springframework.org/schema/mvc"

xmlns:aop="http://springframework.org/schema/aop"

xmlns:cache="http://springframework.org/schema/cache"

xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans-4.0.xsd

http://springframework.org/schema/aop http://springframework.org/schema/aop/spring-aop-4.0.xsd

http://springframework.org/schema/tx http://springframework.org/schema/tx/spring-tx-4.0.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context-4.0.xsd

http://springframework.org/schema/mvc http://springframework.org/schema/mvc/spring-mvc-4.0.xsd

http://springframework.org/schema/cache http://springframework.org/schema/cache/spring-cache.xsd">

十,SpringMVC配置文件

xmlns:context="http://springframework.org/schema/context" xmlns:tx="http://springframework.org/schema/tx" xmlns:mvc="http://springframework.org/schema/mvc"

xmlns:aop="http://springframework.org/schema/aop"

xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans-4.0.xsd

http://springframework.org/schema/aop http://springframework.org/schema/aop/spring-aop-4.0.xsd

http://springframework.org/schema/tx http://springframework.org/schema/tx/spring-tx-4.0.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context-4.0.xsd

http://springframework.org/schema/mvc http://springframework.org/schema/mvc/spring-mvc-4.0.xsd">

application/json;charset=utf-8

text/json;charset=utf-8

xmlns:context="http://springframework.org/schema/context" xmlns:tx="http://springframework.org/schema/tx" xmlns:mvc="http://springframework.org/schema/mvc"

xmlns:aop="http://springframework.org/schema/aop"

xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans-4.0.xsd

http://springframework.org/schema/aop http://springframework.org/schema/aop/spring-aop-4.0.xsd

http://springframework.org/schema/tx http://springframework.org/schema/tx/spring-tx-4.0.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context-4.0.xsd

http://springframework.org/schema/mvc http://springframework.org/schema/mvc/spring-mvc-4.0.xsd">

application/json;charset=utf-8

text/json;charset=utf-8

十一,mybatis配置文件

"http://mybatis.org/dtd/mybatis-3-config.dtd">

十二,log4j

# Set root category priority to INFO and its only appender to CONSOLE.

log4j.rootCategory=DEBUG, CONSOLE

#log4j.rootCategory=INFO, CONSOLE, LOGFILE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender

log4j.appender.CONSOLE.Threshold=DEBUG

log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout

log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} %p - %m%n

log4j.logger.java.sql.Connection=DEBUG

log4j.logger.java.sql.Statement=DEBUG

log4j.logger.java.sql.PreparedStatement=DEBUG

log4j.logger.java.sql.ResultSet=DEBUG

十三,web.xml

xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

TestRedis

contextConfigLocation

classpath:config/applicationContext.xml

log4jConfigLocation

classpath:config/log4j.properties

log4jRefreshInterval

60000

org.springframework.web.context.ContextLoaderListener

org.springframework.web.util.Log4jConfigListener

spring

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:config/SpringMVC.xml

1

spring

*.do

characterEncoding

org.springframework.web.filter.CharacterEncodingFilter

encoding

UTF-8

forceEncoding

true

characterEncoding

*.do

index.jsp

</welcome-file-list>

xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

TestRedis

contextConfigLocation

classpath:config/applicationContext.xml

log4jConfigLocation

classpath:config/log4j.properties

log4jRefreshInterval

60000

org.springframework.web.context.ContextLoaderListener

org.springframework.web.util.Log4jConfigListener

spring

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:config/SpringMVC.xml

1

spring

*.do

characterEncoding

org.springframework.web.filter.CharacterEncodingFilter

encoding

UTF-8

forceEncoding

true

characterEncoding

*.do

index.jsp

</welcome-file-list>

十四,测试,已查询为例(getUser()方法),jsp测试页面整的比较丑就不贴出来了,自己写一个吧。。。

查询前:

执行第一次查询:

执行第二次查询操作:

上图可见,没有再执行sql,直接从redis中获取数据。

以上所述是给大家介绍的Spring与Mybatis基于注解整合Redis的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,会及时回复大家的。在此也非常感谢大家对我们网站的支持!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java内部类之间的闭包和回调详解
下一篇:全面解析Java观察者模式
相关文章

 发表评论

暂时没有评论,来抢沙发吧~