Según el hecho de que encontré varios problemas durante este período de tiempo, pensé en resolverlo. Este artículo presenta principalmente la integración de Redis en forma de anotaciones basadas en Spring+MyBatis. Menos tonterías, llega al punto.
Primero, prepare a Redis. Voy a usar la versión de Windows. Después de descargar, simplemente comience directamente a Redis-Server. Vea la imagen a continuación:
Primero, agregue el paquete jar primero
2. Crear clase de entidad
paquete 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; @Jsonnaming (PropertyNamingStrategy.lowerCaseWithUnderScoresstrategy.class) clase pública Uservo implementa serializable {private estático final long serialversionUid = 1l; private int id; nombre de usuario de cadena privada; contraseña de cadena privada; private intge; público uservo () {super (); } public Uservo (int id, String UserName, String Password, int Age) {super (); this.id = id; this.username = username; this.password = contraseña; this.age = age;} public int getId () {return id;} public void setid (int id) {this.id = id;} public string getUsName () 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;}@Overridepublic String toString() {return "UserVO [id=" + id + ", username=" + nombre de usuario + ", contraseña =" + contraseña + ", edad =" + edad + "]";}} Tres, interfaz DAO
paquete com.sl.user.dao; import com.sl.user.vo.uservo; interfaz pública userdao {public void addUser (uservo user); public void deleteuser (user user); public void updateUser (user user); público uservo getUserByid (int id); public uservo getuser (intd);} 4. Usermapper
<? xml versión = "1.0" encoding = "utf-8"?> <! Doctype mapper public "-// mybatis.org//dtd mapper 3.0 // en" "http://mybatis.org/dtd/mybatis-3-mapper.dtdd"> <mperspace = "com.sl.sl.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user.user > <resultmap id = "userResult" type = "user"> <resultado columna = "id" propiedad = "id"/> <resultado column = "userame" Property = "userame"/> <resultado columna = "contraseña" propiedad = "contraseña"/> <resultado columna = "edad" propiedad = "edad"/> <resultado columna = "edad" propiedad = "edad"/>>/resultMap> <sert id = "adduser" Age " t_user (username, contraseña, edad, edad) valores (#{username},#{contraseña},#{age}) </sert> <update id = "deleteuser" parametertype = "user"> Eliminar * de t_user donde id =#{id} </update> <update id = "updateuser" parametertype = "usuario" User "Usation t_user t_user t_user ty =" test = "test =" test = "test =" test = "test =" test = "test =" test = "test =" test = "test =" test = "test =" test = "test =" test = "test =" test = "tea y nombre de usuario! = '' '"> username = #{username}, </if> <if test =" contraseña! = null y contraseña! =' '"> contraseña = #{contraseña}, </if> <if test =" Age! = Null and Age! =' '' "> Age = #{Age} </if> where 1 = 1 <if test =" Id! = Null e id! = '' '' '' #{id} </if> </update> <select id = "getUser" parameterType = "int" resultType = "user"> select * de t_user donde id = #{id} </select> <select id = "getUserByid" parametertype = "int" dentType = "java.lang.string" #{id} </select> </mapper> 5. Interfaz de servicio
paquete com.sl.user.service; import com.sl.user.vo.uservo; pública interfaz usereraService {public void addUser (uservo user); public void deleteuser (user user); public void UpdateUser (Uservo user); public Uservo getUserByid (int id); público uservo getuser (intd);} Sexto, implementación del servicio
paquete com.sl.user.service.impl; import org.springframework.beans.factory.annotation.aUtowired; import org.springframework.cache.annotation.cacheEvict; import og.springframework.cache.annotation.cacheeVict; import org.springframework.stereotype.service; org.springframework.transaction.annotation.propagation; import org.springframework.transaction.annotation.transactional; import com.sl.user.dao.userdao; import com.sl.user.service.userService; com.sl.user.vo.uservo; @Service ("UserService")@transaccional (propagation = propagation 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 (user user) {userDao.UpdateUser (user);}@anverride@cacheo (valor = "user", key = "getUserByid") public Uservo getUserByid (int id) {return userdao.getuserById (id);}@anverride@cacheo (value = "user", key = "'getUser'") público uservo getUser (int id) {return userDao.getuser (id);}} Siete, Ctrl capa
paquete 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 og.springframework.webind.annotation.ReTremapping; org.springframework.web.bind.annotation.ResponseBody; import com.sl.user.service.userService; import com.sl.user.vo.uservo;@controler@requestmapping ("/userCtrl") clase pública userCtrl {@aUtowiredprivate usserService de usuarios service; @RequestMapping ("/"/"/") publicidad pública oso. Adduser (Uservo User) {Userservice.adduser (user);}@requestmapping ("/deletero") public void deleteuser (user user) {userservice.deleteUser (user);}@requestmapping ("/updateUser") public void UpdateUser (uservo) usuario) {Userservice.UpdateUser (user);}@ResponseBody@requestmapping ("/getUserById") Map público <String, Object> getUserById (user user) {map <string, object> map = new Hashmap <String, Object> (); map.put ("Msg", UserService.getUserByid (4)); 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;}}} 8. Clase clave de Redis, utilizada para operaciones de CRUD
paquete 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 java.io.objectOutputStream; importar org.springframework.cache.cache; importar org.springframework.cache.support.SimpleValueWrapper; importar org.springframework.dao.dataAccessException; importar org.springframework.data.redis.connection.redisconnection; importar org.springframework.data.redis.core.rediscallback; importar org.springframework.data.redis.core.redistemplate; La clase pública redisutil implementa caché {private redistemplate <string, object> redistemplate; nombre de cadena privada; public RedistEmplate <String, Object> getRedistEmplate () {return redistemplate; } public void setRedistEmplate (redistemplate <string, object> redistemplate) {this.redistemplate = redistemplate; } public void setName (nombre de cadena) {this.name = name; } @Override public String getName () {return this.name; } @Override Public Object getNativecache () {return this.redistemplate; } /*** Obtenga la clave de Cache* /@anular public ValueWrapper get (clave de objeto) {System.out.println ("Get Key"); Cadena final KeyF = Key.ToString (); Objeto objeto = nulo; object = redistemplate.ExeCute (new Rediscallback <Sect> () {Public Object doinredis (redisConnection Connection) lanza DataCcessException {byte [] key = keyf.getBytes (); byte [] value = Connection.get (key); if (value == null) {return null;} return toobject (value);}}); return (object! = null? new SimpleValueWrapper (objeto): nulo); } /*** Guardar una nueva clave para el caché*Primero obtenga el nombre y el objeto y luego conviértelo en bytearray* /@anular public void put (clave de objeto, valor de objeto) {system.out.println ("poner clave"); Cadena final KeyF = Key.ToString (); valor del objeto final = valor; Long Livetime final = 86400; redistemplate.exCute (new Rediscallback <Rong> () {public Long doinredis (redisConnection Connection) lanza DataAccessException {byte [] keyb = keyf.getBytes (); byte [] valueB = tobyTearray (valuef); conexión.set (tecla, valueB); if (Livetime> 0) {Conexy.Extire (KeyB, LiVetIMe (KEYB, LIVETIME; return 1l; } byte privado [] tobytearray (object obj) {byte [] bytes = null; ByteArRayOutputStream bos = new ByteArRaReOutputStream (); intente {ObjectOutputStream oos = new ObjectOutputStream (BOS); oos.writeObject (obj); oos.flush (); bytes = bos.tobytearray (); oos.close (); bos.close (); } Catch (ioException ex) {ex.printstacktrace (); } bytes de retorno; } objeto privado toObject (byte [] bytes) {object obj = null; intente {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; } /*** Eliminar la tecla* /@anular public void Evict (clave de objeto) {system.out.println ("del key"); Cadena final KeyF = Key.ToString (); redistemplate.execute (new Rediscallback <Angn> () {public Long doinredis (Redisconnection Connection) lanza DataAccessException {return Connection.del (keyf.getBytes ());}}); } /*** clara clave* /@anular public void clear () {System.out.println ("Clear Key"); redistemplate.execute (new Rediscallback <String> () {public String doinredis (Redisconnection Connection) lanza DataCcessException {Connection.FlushDB (); return "OK";}}); } @Override public <T> t get (clave de objeto, clase <t> type) {return null; } @Override public ValueWrapper Putifabsent (clave de objeto, valor de objeto) {return null; }} 9. Spring integra archivos de configuración de MyBatis y Redis
<? xml versión = "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.springframewframewwringwringw ork.org/schema/aop"xmlns:cache="http://www.springframework.org/schema/cache"xsi:schemalocation="http://www.springframework.org/schema/beanss 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/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache.xsd"> ost -> <context: component-scan base-package = "com.sl.user.service" /> <context: component-scan base-pankage = "com.sl.user.service.*" /> <context: component-scan base-package = "com.sl.user.redis" /> <!-enable anotation-> <context: annotation-config /> <! annotation--><cache:annotation-driven/><!-- MyBatis start --><!-- Configure dataSource DriverManagerDataSource--><bean id="dataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"></property><property name="url" valor = "jdbc: mysql: //127.0.0.1: 3306/test"> </propiety <propiety name = "username" value = "root"> </propial> <propiedad de propiedad = "contraseña" valor = "root"> </propiedad> </bean> <!-myBatis Configuration SqlSessionFactoryFactory-> <Bean id = "Session Factory" ref = "DataSource"> </Property> <Property Name = "configLocation" value = "classpath: config/mybatis.xml"> </property> <propiedad name = "mapperlocations" value = "classpath: mapper/usermapper.xml"> </property> </bean> <!- mybatis automatic escaneo a cargar sql maps/interface: mapePersConferConfiNner SQLSessionFactoryBasePackage: Especifique el paquete donde se encuentra el archivo/interfaz de mapa SQL (interfaz automática)-> <rano> <propiedad name = "sqlsessionfactory" ref = "sessionFactory"> </spertity> <Property name = "BasePackage" value = "com.sl.user.dao"> </property> </bean> <!-TRANSACTION DATASEORCETRETERAURAGER- id = "txManager"> <Property name = "dataSource" ref = "dataSource"> </property> </ Bean> <!-Uso de transacciones declarativas: Referencia al Administrador de transacciones definido anteriormente-> <tx: Annotation-Drivened Transaction-Manager = "TXManager"> </tx: Annotation-Driven> <!-MyBatis End-<! <! <! <! Configurar Redis Connection Pool JEDISpoolConfig-> <Bean ID = "PoolConfig"> <Property Name = "Maxidle" Value = "300" /> <Property Name = "Maxtotal" Value = "600" /> < /Bean> <!-Configurar CoonnectionFactory JedisconnectionFactory-> <bean id = "connfactory"> <Moder Name = "Host name" value = "127.0.0.1"> </propiedad> <propiedad name = "puerto" value = "6379"> </propiedad> <propiedad name = "PoolConfig" ref = "PoolConfig"> </property> </bean> <!-Configurar redistemplate stringRedistemate->> <bean id = "redistemplate"> <nombre de propiedad = "name de conexión" ref. id = "Cachemanager"> <Property Name = "Caches"> <Set> <Bean> <Property Name = "redistemplate" ref = "redistemplate"/> <propiedad name = "name" value = "user"/> <!-El nombre del usuario debe usarse en anotaciones de clase o método-> </bean> </set> </propiety> </ Bean> </ Beans>
10, archivo de configuración de SpringMVC
<? xml versión = "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/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/spring-beans-4.0.xsd http://www.springframework.org/schema/aop 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/><!-- Habilitar la anotación de MVC de primavera-> <context: annotation-conconfig/> <!-Establezca el paquete de jares cuando la clase se encuentra la anotación-> <contextion: context. base-package="com.sl.user.*"></context:component-scan><!-- Resolution of model view name, that is, adding prefixes to model view name--><bean id="viewResolver"><property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/><property name="prefix" valor = "/vistas/"/> <propiedad name = "suffix" value = ". jsp"/> </bean> <Bean> <!-Json Converter-> <Property Name = "MessageConverters"> <List> <Bean> <Property name = "SupportedMediatyPes"> <List> <Value> Application/JSson; Charset = UTF-8 </value> <value> text/json; charset = utf-8 </valor> </list> </property> </bean> </list> </property> </beans> </beans>
11, archivo de configuración de mybatis
<? xml versión = "1.0" encoding = "utf-8"?> < Alias-> <Pyypealiases> <typealias alias = "user" type = "com.sl.user.vo.uservo"/> </typealiases> </figuration>
12, log4j
# Establecer la prioridad de la categoría raíz a la información y su único apéndice a console.log4j.rootcategory = debug, consola# log4j.rootcategory = info, console, logfile# console está configurado para ser un consolepender utilizando un PatternLayout.log4j.appender.console = org.apache.log4j.consoleppenderlog4j.appender.console.threshold = debuglog4j.appender.console.layout = org.apache.log4j.patternlayautlog4j.appender.console.layout.conversionpattern =%%d @ {@patternlaylog4j.appender.console.layout.conversionpattern =%%d @ {ddym-mm-mm-mm-dddy Hh/: mm/: ss} %p - %m %nlog4j.logger.java.sql.connection = debuglog4j.logger.java.sql.statement = debuglog4j.logger.java.sql.preparedstatement = debuglog4j.logger.java.sql. Trece, web.xml
<? xml versión = "1.0" encoding = "utf-8"?> <web-app versión = "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-n AME> <Amam-Value> ClassPath: config/applicationContext.xml </param-value> </context-param> <context-param> <amamname> log4jconfiglocation </param-name> <p aram-value> classpath: config/log4j.properties </param-value> </context-param> <context-param> <amamname> log4jrefreshinterval </param-name> <param-value > 60000 </param-value> </context-param> <Oyerer> <searner-class> org.springframework.web.context.contextloaderListener </ oyinger-class> </oyinger> <!- Log--><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> <amam-value> classpath: config/springmvc.xml </amarr-value> </it-param> <load-on-startup> 1 </load-on-startup> </servlet> <ervlet-mapping> <ervlet-name> spring </servlet-name> <uRl-ptern>*. El problema del código chino confusión -> <filter> <filter-name> caracterescoding </shrey-name> <filter-class> org.springframework.web.filter.CharacteriCterEncodingFilter </filter-class> <Entel-Param> <amamname> encoderando </amam-name> <amam-value> Utf-8 </marr-value> </ init-param> <boram> coding</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>
Catorce, Test, se han consultado como un ejemplo (método getUser ()), la página de prueba JSP es fea, por lo que no lo publicaré, solo escribo uno solo. . .
Antes de la consulta:
Ejecutar la primera consulta:
Realice la segunda operación de consulta:
Como se puede ver en la figura anterior, no se ejecuta nuevamente SQL y los datos se obtienen directamente de Redis.
Lo anterior es el método de integrar Redis basado en anotaciones del editor. Espero que sea útil para todos. Si tiene alguna pregunta, déjame un mensaje y el editor responderá a todos a tiempo. ¡Muchas gracias por su apoyo al sitio web de Wulin.com!