程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Spring與Mybatis基於注解整合Redis的辦法

Spring與Mybatis基於注解整合Redis的辦法

編輯:關於JAVA

Spring與Mybatis基於注解整合Redis的辦法。本站提示廣大學習愛好者:(Spring與Mybatis基於注解整合Redis的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是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

<?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測試頁面整的比擬丑就不貼出來了,本身寫一個吧。。。

查詢前:

履行第一次查詢:

履行第二次查詢操作:

上圖可見,沒有再履行sql,直接從redis中獲得數據。

以上所述是小編給年夜家引見的Spring與Mybatis基於注解整合Redis的辦法,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved