欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-31 21:31:10
基于这段时间折腾redis遇到了各种问题,想着整理一下。本文主要介绍基于spring+mybatis以注解的形式整合redis。废话少说,进入正题。   首先准备re...

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

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

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

一,先上jar包

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

二,创建实体类

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

<?xml version="1.0" encoding="utf-8" ?> 
<!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 
<mapper namespace="com.sl.user.dao.userdao" >
<resultmap id="userresult" type="user">
<result column="id" property="id"/>
<result column="userame" property="userame"/>
<result column="password" property="password"/>
<result column="age" property="age"/>
</resultmap>
<insert id="adduser" parametertype="user">
insert into t_user(username,password,age) values(#{username},#{password},#{age})
</insert>
<update id="deleteuser" parametertype="user">
delete * from t_user where id = #{id}
</update>
<update id="updateuser" parametertype="user">
update t_user set
<if test="username != null and username != ''"> username = #{username},</if>
<if test="password != null and password != ''"> password = #{password},</if>
<if test="age != null and age != ''"> age = #{age}</if>
where 1=1
<if test="id != null and id != ''">and id = #{id}</if>
</update>
<select id="getuser" parametertype="int" resulttype="user" >
select * from t_user where id = #{id}
</select>
<select id="getuserbyid" parametertype="int" resulttype="java.lang.string" >
select username from t_user where id = #{id}
</select>
</mapper>

五,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="getuserbyid")
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<string,object> getuserbyid(uservo user){
map<string,object> map = new hashmap<string,object>();
map.put("msg",userservice.getuserbyid(4));
return map;
}
@responsebody
@requestmapping("/getuser")
public map<string,object> getuser(uservo vo){
map<string,object> map = new hashmap<string,object>();
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<string, object> redistemplate; 
private string name; 
public redistemplate<string, object> getredistemplate() { 
return redistemplate; 
} 
public void setredistemplate(redistemplate<string, object> 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<object>() { 
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<long>() { 
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<long>() { 
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<string>() { 
public string doinredis(redisconnection connection) 
throws dataaccessexception { 
connection.flushdb(); 
return "ok"; 
} 
}); 
} 
@override 
public <t> t get(object key, class<t> type) { 
return null; 
} 
@override 
public valuewrapper putifabsent(object key, object value) { 
return null; 
} 
}

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

<?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:context="http://www.springframework.org/schema/context" 
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- 扫描dao,service -->
<context:component-scan base-package="com.sl.user.service" />
<context:component-scan base-package="com.sl.user.service.*" />
<context:component-scan base-package="com.sl.user.redis" />
<!-- 启用注解 -->
<context:annotation-config/>
<!-- 启动缓存注解 -->
<cache:annotation-driven/>
<!-- mybatis start -->
<!-- 配置datasource drivermanagerdatasource-->
<bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource">
<property name="driverclassname" value="com.mysql.jdbc.driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- mybatis配置 sqlsessionfactorybean -->
<bean id="sessionfactory" class="org.mybatis.spring.sqlsessionfactorybean">
<property name="datasource" ref="datasource"></property>
<property name="configlocation" value="classpath:config/mybatis.xml"></property>
<property name="mapperlocations" value="classpath:mapper/usermapper.xml"></property>
</bean>
<!-- mybatis自动扫描加载sql映射文件/接口 : mapperscannerconfigurer 
sqlsessionfactory
basepackage:指定sql映射文件/接口所在的包(自动扫描) -->
<bean class="org.mybatis.spring.mapper.mapperscannerconfigurer">
<property name="sqlsessionfactory" ref="sessionfactory"></property>
<property name="basepackage" value="com.sl.user.dao"></property>
</bean>
<!-- 事务管理 datasourcetransactionmanager-->
<bean id="txmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
<property name="datasource" ref="datasource"></property>
</bean>
<!-- 使用声明式事务 transaction-manager:引用上面定义的事务管理器-->
<tx:annotation-driven transaction-manager="txmanager"></tx:annotation-driven>
<!-- mybatis end -->
<!-- 配置redis部分 start -->
<!-- 配置redis连接池 jedispoolconfig-->
<bean id="poolconfig" class="redis.clients.jedis.jedispoolconfig">
<property name="maxidle" value="300" /> 
<property name="maxtotal" value="600" /> 
</bean> 
<!-- 配置coonnectionfactory jedisconnectionfactory-->
<bean id="connfactory" class="org.springframework.data.redis.connection.jedis.jedisconnectionfactory">
<property name="hostname" value="127.0.0.1"></property>
<property name="port" value="6379"></property>
<property name="poolconfig" ref="poolconfig"></property>
</bean>
<!-- 配置redistemplate stringredistemplate-->
<bean id="redistemplate" class="org.springframework.data.redis.core.stringredistemplate">
<property name="connectionfactory" ref="connfactory"/>
</bean>
<bean id="cachemanager" class="org.springframework.cache.support.simplecachemanager"> 
<property name="caches"> 
<set> 
<bean class="com.sl.user.redis.redisutil"> 
<property name="redistemplate" ref="redistemplate" /> 
<property name="name" value="user"/> 
<!-- user名称要在类或方法的注解中使用 --> 
</bean> 
</set> 
</property> 
</bean>
</beans>

十,springmvc配置文件

<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<mvc:annotation-driven/>
<!-- 启用spring mvc 注解 -->
<context:annotation-config/>
<!-- 设置使用注解的类所在的jar包 -->
<context:component-scan base-package="com.sl.user.*"></context:component-scan>
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean id="viewresolver" class="org.springframework.web.servlet.view.internalresourceviewresolver">
<property name="viewclass" value="org.springframework.web.servlet.view.jstlview"/>
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.requestmappinghandleradapter">
<!-- json转换器 -->
<property name="messageconverters">
<list>
<bean class="org.springframework.http.converter.json.mappingjackson2httpmessageconverter">
<property name="supportedmediatypes">
<list>
<value>application/json;charset=utf-8</value>
<value>text/json;charset=utf-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
</beans>

十一,mybatis配置文件

<?xml version="1.0" encoding="utf-8"?>
<!doctype configuration public "-//mybatis.org//dtd config 3.0//en" 
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 实体类,简称 -设置别名 -->
<typealiases>
<typealias alias="user" type="com.sl.user.vo.uservo" />
</typealiases>
</configuration>

十二,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

<?xml version="1.0" encoding="utf-8"?>
<web-app version="3.0" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.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">
<display-name>testredis</display-name>
<context-param>
<param-name>contextconfiglocation</param-name>
<param-value>
classpath:config/applicationcontext.xml
</param-value>
</context-param>
<context-param>
<param-name>log4jconfiglocation</param-name>
<param-value>classpath:config/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jrefreshinterval</param-name>
<param-value>60000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
</listener>
<!-- 日志 -->
<listener>
<listener-class>org.springframework.web.util.log4jconfiglistener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>
<init-param>
<param-name>contextconfiglocation</param-name>
<param-value>classpath:config/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 解决中文乱码问题 -->
<filter>
<filter-name>characterencoding</filter-name>
<filter-class>org.springframework.web.filter.characterencodingfilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceencoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterencoding</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

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

查询前:

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

执行第一次查询:

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

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

执行第二次查询操作:

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

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

以上所述是小编给大家介绍的spring与mybatis基于注解整合redis的方法,希望对大家有所帮助