前言:菜鸡一枚,本来想把redis配置在aop中,结果aop一直没配置好,只好把redis部分写到service层。
希望大家有问题或者有什么改进的能给我留言。
pom文件,由于参考了很多网上的方法,可能有些包根本没用到。
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.test</groupId> <artifactId>demo</artifactId> <version>1.0-SNAPSHOT</version> <url>http://maven.apache.org</url> <!-- 用来设置版本号 --> <properties> <srping.version>4.0.2.RELEASE</srping.version> <mybatis.version>3.2.8</mybatis.version> <slf4j.version>1.7.12</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <!-- 用到的jar包 --> <dependencies> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- 表示开发的时候引入,发布的时候不会加载此包 --> <scope>test</scope> </dependency> <!-- java ee包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- spring框架包 start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.10</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${srping.version}</version> </dependency> <!-- spring框架包 end --> <!-- mybatis框架包 start --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- mybatis框架包 end --> <!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</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>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>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.6</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上传组件包 start --> <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.10</version> </dependency> <!-- Redis 相关依赖 --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.1.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.3</version> </dependency> <!-- 上传组件包 end --> </dependencies> <build> <finalName>demo</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!--jetty插件--> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <configuration> <stopPort>9988</stopPort> <stopKey>foo</stopKey> <scanIntervalSeconds>5</scanIntervalSeconds> <connectors> <!--<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">--> <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"> <port>8080</port> <maxIdleTime>60000</maxIdleTime> </connector> </connectors> <webAppConfig> <contextPath>/</contextPath> <defaultsDescriptor></defaultsDescriptor> </webAppConfig> </configuration> </plugin> </plugins> </build> </project>
spring配置,网上找的大神的配置,照搬过来的
applicationContext.xml
<?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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 使用注解式注入 --> <context:annotation-config /> <!-- 自动扫描 --> <context:component-scan base-package="com.chillax" /> <!-- 导入DAO配置 --> <import resource="spring-dao.xml"/> <!-- 导入数据库配置 --> <import resource="spring-db.xml"/> <!-- 导入数据库配置 --> <import resource="spring-tx.xml"/> <!--<!– 导入aop配置 –>--> <!--<import resource="spring-aop.xml"/>--> </beans>spring-dao.xml
<?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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--basePackage指定要扫描的包,在此包之下的映射器都会被搜索到。 可指定多个包,包与包之间用逗号或分号分隔--> <property name="basePackage" value="com.chillax.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> </beans>
spring-db.xml
<?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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> </beans>
spring-tx.xml
<?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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>spring-mvc.xml
<?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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 添加注解驱动 --> <mvc:annotation-driven /> <mvc:default-servlet-handler/> <!-- 设置使用注解的类所在的包 --> <context:component-scan base-package="com.chillax.controller" /> <!-- 完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> </beans>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> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!-- 加载spring bean --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 编码过滤器 --> <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> <!-- 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>/WEB-INF/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> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>jsp页面
<%@ page language="java" pageEncoding="utf-8"%> <html> <script src="jquery-1.6.3.js"> </script> <body> <h2>Hello World!</h2> <table id="table"> </table> <input type="text" name="id" id="id"/> <button type="button" οnclick="select()">查找</button> <script> function select() { var id = $("#id").val(); $.ajax({ method: "post", url: "user/selectuser", data: {id: id}, datatype: "json", success: function (e) { console.log(e); } }); } $(function () { $.ajax({ method:"post", url:"user/userList", datatype:"json", success:function (e) { for(var i=0;i<e.length;i++) { var table=document.getElementById("table"); var row=table.insertRow(); var cell=row.insertCell(0); cell.innerHTML="<td>"+e[i].id+"</td>" cell=row.insertCell(1); cell.innerHTML="<td>"+e[i].name+"</td>" cell=row.insertCell(2); cell.innerHTML="<td>"+e[i].password+"</td>" cell=row.insertCell(3); cell.innerHTML="<td>"+e[i].age+"</td>" } } }) }) </script> </body> </html>jdbc.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/test username=sr password=123456 #定义初始连接数 initialSize=0 #定义最大连接数 maxActive=20 #定义最大空闲 maxIdle=20 #定义最小空闲 minIdle=1 #定义最长等待时间 maxWait=60000log4j.properties(还是贴出来吧,这个日志貌似没用到)
#定义LOG输出级别 log4j.rootLogger=INFO,Console,File #定义日志输出目的地为控制台 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out #可以灵活地指定日志输出格式,下面一行是指定具体的格式 log4j.appender.Console.layout = org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n #文件大小到达指定尺寸的时候产生一个新的文件 log4j.appender.File = org.apache.log4j.RollingFileAppender #指定输出目录 log4j.appender.File.File = logs/ssm.log #定义文件最大大小 log4j.appender.File.MaxFileSize = 10MB # 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志 log4j.appender.File.Threshold = ALL log4j.appender.File.layout = org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%nusercontroller
package com.chillax.controller; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import com.alibaba.fastjson.JSON; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.chillax.dto.User; import com.chillax.service.IUserService; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/user") public class UserController { @Resource private IUserService userService; @ResponseBody @RequestMapping("/userList") public Object userList(){ List<User> uList = userService.getAllUser(); return JSON.toJSON(uList); } @ResponseBody @RequestMapping("/selectuser") public Object select(HttpServletRequest request){ int id=Integer.parseInt(request.getParameter("id")); return JSON.toJSON(userService.getUserById(id)); } }IUserService
package com.chillax.service; import java.util.List; import com.chillax.dto.User; public interface IUserService { public User getUserById(int userId); public List<User> getAllUser(); }UserServiceImpl
package com.chillax.service.Impl; import java.util.List; import javax.annotation.Resource; import com.chillax.redis.RedisClient; import org.springframework.stereotype.Service; import com.chillax.dao.IUserDao; import com.chillax.dto.User; import com.chillax.service.IUserService; @Service("userService") public class UserServiceImpl implements IUserService { @Resource private IUserDao userDao; static private RedisClient redisClient=new RedisClient(); public User getUserById(int userId) { User user = (User) redisClient.get(userId+""); if(user==null) { user = userDao.queryByPrimaryKey(userId); redisClient.set(userId+"",user); } return user; } @Override public List<User> getAllUser() { return userDao.getAllUser(); } }IUserDao
package com.chillax.dao; import java.util.List; import java.util.Map; import com.chillax.dto.User; public interface IUserDao { public User queryByPrimaryKey(Integer id); public List<User> queryUserByBatch(Map<String,Object> params); public void insertUser(User user); public void insertUserByBatch(List<User> list); public void deleteByPrimaryKey(Integer id); public void delteUserByBatch(Map<String,Object> params); public void updateByPrimaryKey(Integer id); public List<User> getAllUser(); }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.chillax.dao.IUserDao" > <resultMap id="BaseResultMap" type="com.chillax.dto.User"> <result column="id" property="id" jdbcType="INTEGER" /> <result column="name" property="name" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="age" property="age" jdbcType="INTEGER" /> </resultMap> <sql id="Base_Column_List"> id, name, password, age </sql> <!-- 查询用户--> <select id="queryByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer"> select <include refid="Base_Column_List" /> from user where id = #{id,jdbcType=INTEGER} </select> <!-- 查询用户--> <select id="getAllUser" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from user </select> <!-- 批量查询用户--> <select id="queryUserByBatch" resultMap="BaseResultMap" parameterType="java.util.Map"> select <include refid="Base_Column_List" /> from user where id in <foreach collection="idList" item="userId" index="index" open="(" separator="," close=")"> #{userId,jdbcType=DECIMAL} </foreach> </select> <!-- 插入用户 --> <insert id="insertUser" parameterType="com.chillax.dto.User"> insert into user <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="name != null" > name, </if> <if test="password != null" > password, </if> <if test="age != null" > age, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="name != null" > #{name,jdbcType=VARCHAR}, </if> <if test="password != null" > #{password,jdbcType=VARCHAR}, </if> <if test="age != null" > #{age,jdbcType=INTEGER}, </if> </trim> </insert> <!-- 批量插入用户 --> <insert id="insertUserByBatch" parameterType="java.util.List" > insert into USER (ID, NAME, PASSWORD, AGE) select A.* from ( <foreach collection="list" item="user" index="index" separator="union"> select #{user.id,jdbcType=INTEGER}, #{user.name,jdbcType=VARCHAR}, #{user.password,jdbcType=VARCHAR}, #{user.age,jdbcType=INTEGER} from dual </foreach> ) A </insert> <!-- 删除用户 --> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from user where id = #{id,jdbcType=INTEGER} </delete> <!-- 批量删除用户 --> <delete id="deleteUserByBatch" parameterType="java.util.Map" > delete from user where id IN <foreach item="ids" collection="iList" open="(" separator="," close=")"> #{ids,jdbcType=DECIMAL} </foreach> </delete> <!-- 更新用户 --> <update id="updateByPrimaryKey" parameterType="com.chillax.dto.User" > update user <set > <if test="name != null" > name = #{name,jdbcType=VARCHAR}, </if> <if test="password != null" > password = #{password,jdbcType=VARCHAR}, </if> <if test="age != null" > age = #{age,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> </mapper>实体类User;注意一定要实现Serializable接口
package com.chillax.dto; import java.io.Serializable; public class User implements Serializable{ private Integer id; private String name; private String password; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }RedisClient
package com.chillax.redis; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import com.chillax.dto.User; import com.chillax.util.SerializeUtil; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPool; import redis.clients.jedis.SortingParams; public class RedisClient { private Jedis jedis;//非切片额客户端连接 private JedisPool jedisPool;//非切片连接池 private ShardedJedis shardedJedis;//切片额客户端连接 private ShardedJedisPool shardedJedisPool;//切片连接池 public RedisClient() { initialPool(); initialShardedPool(); shardedJedis = shardedJedisPool.getResource(); jedis = jedisPool.getResource(); } /** * 初始化非切片池 */ private void initialPool() { // 池基本配置 JedisPoolConfig config = new JedisPoolConfig(); // config.setMaxActive(20); config.setMaxIdle(5); // config.setMaxWait(1000l); config.setTestOnBorrow(false); jedisPool = new JedisPool(config,"127.0.0.1",6379); } /** * 初始化切片池 */ private void initialShardedPool() { // 池基本配置 JedisPoolConfig config = new JedisPoolConfig(); // config.setMaxActive(20); config.setMaxIdle(5); // config.setMaxWait(1000l); config.setTestOnBorrow(false); // slave链接 List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); shards.add(new JedisShardInfo("127.0.0.1", 6379, "master")); // 构造池 shardedJedisPool = new ShardedJedisPool(config, shards); } public void show() { KeyOperate(); // add(); // StringOperate(); // ListOperate(); // SetOperate(); // SortedSetOperate(); // HashOperate(); jedisPool.returnResource(jedis); shardedJedisPool.returnResource(shardedJedis); } public Object get(String key){ System.out.println("从redis中获取"); if(shardedJedis.exists(key.getBytes())){ return SerializeUtil.unserialize(shardedJedis.get(key.getBytes())); }else{ return null; } } public void set(String key,Object object){ System.out.println("存放到redis"); shardedJedis.set(key.getBytes(),SerializeUtil.serialize(object)); } private void add(){ User user=new User(); user.setId(2); user.setAge(1); user.setName("hah"); user.setPassword("123"); shardedJedis.set("5".getBytes(),SerializeUtil.serialize(user)); System.out.println("系统中所有键如下:"); Set<String> keys = jedis.keys("*"); Iterator<String> it=keys.iterator() ; while(it.hasNext()){ String k = it.next(); System.out.println(k); } } private void KeyOperate() { System.out.println("======================key=========================="); System.out.println("系统中所有键如下:"); Set<String> keys = jedis.keys("*"); Iterator<String> it=keys.iterator() ; while(it.hasNext()){ String key = it.next(); System.out.println(key); } // 清空数据 // System.out.println("清空库中所有数据:"+jedis.flushDB()); // // 判断key否存在 // System.out.println("判断key999键是否存在:"+shardedJedis.exists("key999")); // System.out.println("新增key001,value001键值对:"+shardedJedis.set("key001", "value001")); // System.out.println("判断key001是否存在:"+shardedJedis.exists("key001")); // // 输出系统中所有的key // System.out.println("新增key002,value002键值对:"+shardedJedis.set("key002", "value002")); // // // 删除某个key,若key不存在,则忽略该命令。 // System.out.println("系统中删除key002: "+jedis.del("key002")); // System.out.println("判断key002是否存在:"+shardedJedis.exists("key002")); // // 设置 key001的过期时间 // System.out.println("设置 key001的过期时间为5秒:"+jedis.expire("key001", 5)); // try{ // Thread.sleep(2000); // } // catch (InterruptedException e){ // } // // 查看某个key的剩余生存时间,单位【秒】.永久生存或者不存在的都返回-1 // System.out.println("查看key001的剩余生存时间:"+jedis.ttl("key001")); // // 移除某个key的生存时间 // System.out.println("移除key001的生存时间:"+jedis.persist("key001")); // System.out.println("查看key001的剩余生存时间:"+jedis.ttl("key001")); // // 查看key所储存的值的类型 // System.out.println("查看key所储存的值的类型:"+jedis.type("key001")); /* * 一些其他方法:1、修改键名:jedis.rename("key6", "key0"); * 2、将当前db的key移动到给定的db当中:jedis.move("foo", 1) */ } } class Main{ public static void main(String[] args) { // TODO Auto-generated method stub new RedisClient().show(); } }序列化工具SerizlizeUtil
package com.chillax.util; import java.io.*; public class SerializeUtil implements Serializable{ public static byte[] serialize(Object object) { ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; try { //序列化 baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(object); byte[] bytes = baos.toByteArray(); return bytes; } catch (Exception e) { e.printStackTrace(); return null; } } 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) { return null; } } }