耀眼的橘子的gravatar头像
耀眼的橘子 2017-02-27 16:19:52
ssm+redis+maven集成使用Jedis客户端demo

上次写完了一个demo 之后想把redis技术用在项目中,结果是频频报错。后来才发现原来我把两种实现方法混为一谈了,这次我向大家介绍第二种,我结合项目写的redis-demo。希望大家哆嗦多多收益,在看代码之前,我觉得有必要跟讲解一下 jedis 的运行原理:

1.插入一条数据 :

ssm+redis+maven集成使用Jedis客户端demo

2.查询刚才插入的方法:

ssm+redis+maven集成使用Jedis客户端demo

3.第二次查询:

ssm+redis+maven集成使用Jedis客户端demo

4.修改刚才插入的数据:

ssm+redis+maven集成使用Jedis客户端demo

5.查询修改过的数据:

ssm+redis+maven集成使用Jedis客户端demo

好了,了解了运行机制,我们运行代码就会明白很多。

在pom.xml文件中:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.basessm</groupId>
  <artifactId>basessm</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>basessm Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <properties>
		<!-- spring版本号 -->
		<spring.version>4.0.2.RELEASE</spring.version>
		<!-- mybatis版本号 -->
		<mybatis.version>3.2.6</mybatis.version>
		<!-- log4j日志文件管理包版本 -->
		<slf4j.version>1.7.7</slf4j.version>
		<log4j.version>1.2.17</log4j.version>
	</properties>
  
  <dependencies>
  
  		<!-- 配置 redis  start-->
  		<!-- Ehcache实现,用于参考 -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-ehcache</artifactId>
		    <version>1.0.0</version>
		</dependency>
  		<dependency> 
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.0.2.RELEASE</version>
		</dependency>
		<dependency>
		    <groupId>org.apache.commons</groupId>
		    <artifactId>commons-lang3</artifactId>
		    <version>3.5</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.1.0</version>
		</dependency>
  		
  		<!-- 配置 redis  end-->
  
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
			<scope>test</scope>
		</dependency>
		<!-- spring核心包 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- mybatis核心包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<!-- mybatis/spring包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.2</version>
		</dependency>
		<!-- 导入java ee jar 包 -->
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>7.0</version>
		</dependency>
		<!-- 导入Mysql数据库链接jar包 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.30</version>
		</dependency>
		<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.2.2</version>
		</dependency>
		<!-- JSTL标签类 -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- 日志文件管理包 -->
		<!-- log start -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		
		<!-- 格式化对象,方便输出日志 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.41</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<!-- log end -->
		<!-- 映入JSON -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		<!-- 上传组件包 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>
		
		<!-- aop注解  -->
          
          <dependency>
             <groupId>org.aspectj</groupId>
             <artifactId>aspectjrt</artifactId>
              <version>1.6.12</version>
        </dependency>
         <dependency>
             <groupId>org.aspectj</groupId>
             <artifactId>aspectjweaver</artifactId>
            <version>1.6.12</version>
         </dependency>
         <dependency>
             <groupId>cglib</groupId>
             <artifactId>cglib</artifactId>
              <version>2.2</version>
         </dependency>
		
		
	</dependencies>
	
  <build>
    <finalName>basessm</finalName>
  </build>
</project>

在application.xml文件中: 重点看 红色标注的地方


  
	<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" /> 
		<!-- 自动扫描mapping.xml文件 -->
		<property name="configLocation" value="classpath:com/basessm/dao/mybatis-config.xml" />
	</bean>
	

在mybatis-conf.xml文件中。开启全局缓存:

<?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>  

	<settings>  
	    <!-- 这个配置使全局的映射器启用或禁用缓存 -->  
	    <setting name="cacheEnabled" value="true" />  
	 <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->      
	        <setting name="multipleResultSetsEnabled" value="true"/>  
	    <!-- 配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 -->  
	    <setting name="defaultExecutorType" value="REUSE" />  
	    <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->  
	    <setting name="lazyLoadingEnabled" value="false" />  
	    <setting name="aggressiveLazyLoading" value="true" />  
	    <!-- <setting name="enhancementEnabled" value="true"/> -->  
	    <!-- 设置超时时间,它决定驱动等待一个数据库响应的时间。 -->  
	    <setting name="defaultStatementTimeout" value="25000" />  
	</settings> 
	<mappers>
		<mapper resource="com/basessm/dao/UserMapper.xml"/>
	</mappers>
</configuration> 

在UserMapper.xml文件中:

<?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.basessm.dao.UserMapper">  
<cache type="com.basessm.redis.core1.RedisCache" />

<insert id="add" parameterType="com.basessm.model.User" flushCache="true">  
   INSERT INTO user (id,username,password) VALUES (#{id},#{username},#{password})  
</insert>  
 
<delete id="del" parameterType="int">  
    DELETE FROM user WHERE id=#{id}  
</delete>  

<update id="update" parameterType="com.basessm.model.User" >  
    update user
		set id=#{id}
		<if test="username !=null and username !=''">
			,username = #{username}
		</if>
		<if test="password !=null and password !=''">
			,password = #{password}
		</if>
		WHERE id=#{id}
</update> 

<select id="selById" parameterType="com.basessm.model.User" resultType="com.basessm.model.User">  
    SELECT id,username,password FROM user WHERE id=#{id}  
</select>  

<select id="login" parameterType="com.basessm.model.User" resultType="com.basessm.model.User" >  
    SELECT id,username,password FROM user where username=#{username} and password=#{password}
</select> 
<select id="selAll" parameterType="com.basessm.model.User" resultType="com.basessm.model.User" >  
    SELECT id,username,password FROM user
</select> 

</mapper>

创建RedisCache,实现Cache接口:

package com.basessm.redis.core1;

import java.io.Serializable;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.commons.lang3.SerializationUtils;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

import com.basessm.redis.core.SerializeUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;

public class RedisCache implements Cache {
	/**
	 * 日志
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(RedisCache.class);
	private static final long serialVersionUID = -8198240627840132613L;

	/**
	 * The {@code ReadWriteLock}.
	 */
	private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
	/**
	 * Jedis客户端
	 */
	@Autowired
	private Jedis redisClient = createClient();
	private String id;

	public RedisCache(final String id) {
		if (id == null) {
			throw new IllegalArgumentException("必须传入ID");
		}
		System.out.println("............MybatisRedisCache:id=" + id);
		LOGGER.debug("MybatisRedisCache:id=" + id);
		this.id = id;
	}

	@Override
	public void clear() {
		redisClient.flushDB();
	}

	@Override
	public String getId() {
		return this.id;
	}

	@Override
	public Object getObject(Object key) {
		byte[] ob = redisClient.get(SerializeUtil.serialize(key.toString()));
		if (ob == null) {
			return null;
		}
		Object value = SerializeUtil.unSerialize(ob);
		LOGGER.debug("获取的键值对>>>>>>>>>>>>>>>>>>>>>>>>getObject:" + key + "=" + value);
		return value;
	}

	@Override
	public ReadWriteLock getReadWriteLock() {
		return readWriteLock;
	}

	@Override
	public int getSize() {
		return Integer.valueOf(redisClient.dbSize().toString());
	}

	@Override
	public void putObject(Object key, Object value) {
		LOGGER.debug("存入的键值对>>>>>>>>>>>>>>>>>>>>>>>>putObject:" + key + "=" + value);
		redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));
	}

	@Override
	public Object removeObject(Object key) {
		return redisClient.expire(SerializeUtil.serialize(key.toString()), 0);
	}

	protected static Jedis createClient() {
		try {
			JedisPool pool = new JedisPool(new JedisPoolConfig(), "127.0.0.1",6379,8000,"foobared");
			return pool.getResource();
		} catch (Exception e) {
			e.printStackTrace();
		}
		throw new RuntimeException("初始化连接池错误");
	}

}

在项目运行之前启动 redis服务,

JedisPool pool = new JedisPool(new JedisPoolConfig(), "127.0.0.1",6379,8000,"foobared");

分别是连接IP,端口,连接启动时长,密码。

创建序列化类SerializeUtil:

package com.basessm.redis.core;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {
	/**
	 * 
	 * 序列化
	 */
	public static byte[] serialize(Object obj) {

		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;

		try {
			// 序列化
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);

			oos.writeObject(obj);
			byte[] byteArray = baos.toByteArray();
			return byteArray;

		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * 反序列化
	 * 
	 * @param bytes
	 * @return
	 */
	public static Object unSerialize(byte[] bytes) {

		ByteArrayInputStream bais = null;

		try {
			// 反序列化为对象
			bais = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			return ois.readObject();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

创建控制类:

package com.basessm.controller;

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.basessm.model.User;
import com.basessm.service.UserServiceI;

@Controller
@RequestMapping("redisTest")
public class RedisTestCon {
	
	@Autowired
	private UserServiceI userService;
	
	@RequestMapping("/addUser")
	public void addUser(){
		User user = new User();
		user.setId(6);
		user.setUsername("tom6");
		user.setPassword("123456");
		int a = userService.add(user);
		System.out.println("添加用户测试:" + a);
	}
	
	@RequestMapping("/selUser")
	@ResponseBody
	public User selUser(){
		User user = userService.selById(5);
		System.out.println("第一次 :" + user.getUsername());
		User user2 = userService.selById(5);
		System.out.println("第二次 :" + user2.getUsername());
		return user;
	}
	@RequestMapping("/sel")
	@ResponseBody
	public User sel(){
		User user = userService.selById(4);
		System.out.println("第一次 :" + user.getUsername());
		User user2 = userService.selById(4);
		System.out.println("第二次 :" + user2.getUsername());
		return user;
	}
	/**
	 * 修改数据,
	 * @return
	 */
	@RequestMapping("/updUser")
	@ResponseBody
	public User updUser(){
		User user = new User();
		user.setId(5);
		user.setUsername("tom5");
		user.setPassword("alice");
		
		int su = userService.updat(user);
		System.out.println("su:" + su);
		System.out.println("获取修改后的:" + user.getPassword());
		User user2 = userService.selById(5);
		System.out.println("获取修改后的查询 :" + user2.getUsername());
		return user;
	}
	
}

在Controller 里面直接测试,注意看后台日志

关于后台日志的配置:log4.properties:

log4j.rootLogger=DEBUG, stdout    
        
log4j.appender.stdout=org.apache.log4j.ConsoleAppender    
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout    
log4j.appender.stdout.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n    
    
#log4j.appender.R=org.apache.log4j.DailyRollingFileAppender    
#log4j.appender.R.File=../logs/service.log    
#log4j.appender.R.layout=org.apache.log4j.PatternLayout    
#log4j.appender.R.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n    
    
#log4j.logger.com.ibatis = debug    
#log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = debug    
#log4j.logger.com.ibatis.common.jdbc.ScriptRunner = debug    
#log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug    
#log4j.logger.java.sql.Connection = debug    
log4j.logger.java.sql.Statement = debug    
log4j.logger.java.sql.PreparedStatement = debug    
log4j.logger.java.sql.ResultSet =debug   

如果看的不是太明白,推荐大家一个原文网址,里面有详细配置后台打印日志,个人觉得比较好,推荐给大家:

http://blog.csdn.net/win7system/article/details/52014413

日志配置好后,别忘记加入web.xml文件里

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">
	<display-name>Archetype Created Web Application</display-name>
	<!-- Spring和mybatis的配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-mybatis.xml,classpath:applicationContext.xml</param-value>
	</context-param>
	<!-- 编码过滤器 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<async-supported>true</async-supported>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4.properties</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	
	<!-- Spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 防止Spring内存溢出监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<!-- Spring MVC servlet -->
	<servlet>
		<servlet-name>SpringMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringMVC</servlet-name>
		<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>/index.jsp</welcome-file>
	</welcome-file-list>

</web-app>

好了 启动一下项目看看。如有疑问欢迎询问,写的不好的地方,也请大家多多见谅,勿喷,我只是记录一下,怕自己以后忘记!能帮到最好,帮不到请忽略,谢谢


打赏
最近浏览
luolukka  LV8 2020年9月17日
2537863238 2020年8月31日
暂无贡献等级
asoar8  LV1 2020年8月14日
hewo105 2020年6月22日
暂无贡献等级
昵称zzz  LV13 2020年6月13日
haoayou  LV8 2020年6月9日
yynbyynb 2020年5月28日
暂无贡献等级
longjuan104 2020年5月28日
暂无贡献等级
123456liga  LV11 2020年5月22日
郭玉婷  LV10 2020年5月18日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友