java:redis(java代码操作redis,实体类mapper生成器(generator))
1.redis_demo Maven
ItemMapper.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.redis.mapper.ItemMapper" > <resultMap id="BaseResultMap" type="com.redis.model.Item" > <!-- WARNING - @mbg.generated --> <id column="id" property="id" jdbcType="BIGINT" /> <result column="title" property="title" jdbcType="VARCHAR" /> <result column="sell_point" property="sellPoint" jdbcType="VARCHAR" /> <result column="price" property="price" jdbcType="BIGINT" /> <result column="num" property="num" jdbcType="INTEGER" /> <result column="barcode" property="barcode" jdbcType="VARCHAR" /> <result column="image" property="image" jdbcType="VARCHAR" /> <result column="cid" property="cid" jdbcType="BIGINT" /> <result column="status" property="status" jdbcType="TINYINT" /> <result column="created" property="created" jdbcType="TIMESTAMP" /> <result column="updated" property="updated" jdbcType="TIMESTAMP" /> </resultMap> </mapper>
mybatis-config.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> <!-- mybatis默认是没有开启延迟加载的 需要手动开启 --> <settings> <!-- 延迟加载 默认false --> <setting name="lazyLoadingEnabled" value="true" /> <!-- 积极加载 默认true --> <setting name="aggressiveLazyLoading" value="false" /> <!--开启缓存--> <setting name="cacheEnabled" value="true"/> </settings> </configuration>
applicationContext-db.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--数据源配置 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件,**表示迭代查找 --> <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml" /> <!--mybatis配置文件位置 --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" /> </bean> <!--扫描com.redis下的mapper接口 --> <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.redis" /> <!--使用mybatis通用mapper插件 --> <property name="properties"> <value> mappers=tk.mybatis.mapper.common.Mapper </value> </property> </bean> </beans>
applicationContext-redis.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd"> <!-- 配置redis自带的连接池配置(jedisPool) --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!-- 最大连接数 --> <property name="maxTotal" value="30" /> <!-- 最大空闲连接数 --> <property name="maxIdle" value="10" /> <!-- 每次释放连接的最大数目 --> <property name="numTestsPerEvictionRun" value="1024" /> <!-- 释放连接的扫描间隔(毫秒) --> <property name="timeBetweenEvictionRunsMillis" value="30000" /> <!-- 连接最小空闲时间 --> <property name="minEvictableIdleTimeMillis" value="1800000" /> <!-- 连接空闲多久后释放, 当空闲时间>该值且空闲连接>最大空闲连接数时直接释放 --> <property name="softMinEvictableIdleTimeMillis" value="10000" /> <!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 --> <property name="maxWaitMillis" value="1500" /> <!-- 在获取连接的时候检查有效性, 默认false --> <property name="testOnBorrow" value="false" /> <!-- 在空闲时检查有效性, 默认false --> <property name="testWhileIdle" value="true" /> <!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true --> <property name="blockWhenExhausted" value="false" /> </bean> <!-- redis数据库集群连接池配置 --> <bean id="jedisCluster" class="redis.clients.jedis.JedisCluster"> <!-- 首先要把连接池的配置信息引入 --> <constructor-arg name="poolConfig" ref="jedisPoolConfig" /> <!-- 然后需要配置集群中各个节点信息 eg:因为redis最少需要6台服务器(称之为6个节点) --> <constructor-arg name="nodes"> <set> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="${redis.host1}" /><!-- 每一台节点的ip地址 --> <constructor-arg name="port" value="${redis.port1}" /><!-- 每一台redis节点的端口号 --> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="${redis.host2}" /> <constructor-arg name="port" value="${redis.port2}" /> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="${redis.host3}" /> <constructor-arg name="port" value="${redis.port3}" /> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="${redis.host4}" /> <constructor-arg name="port" value="${redis.port4}" /> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="${redis.host5}" /> <constructor-arg name="port" value="${redis.port5}" /> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="${redis.host6}" /> <constructor-arg name="port" value="${redis.port6}" /> </bean> </set> </constructor-arg> </bean> <bean id="redisService" class="com.redis.service.impl.RedisServiceImpl"> <property name="jedisCluster" ref="jedisCluster"></property> </bean> </beans>
applicationContext-tx.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 事务详情 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- read-only="true" 该事务为只读事务 --> <tx:method name="select*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="get*" read-only="true" /> <tx:method name="query*" read-only="true" /> <tx:method name="*" /> </tx:attributes> </tx:advice> <!--支持基于注解的aspectj --> <aop:aspectj-autoproxy /> <!--aop编程,切入点表达式 确定增强的连接器,从而获得切入点 为什么aop这里切service而不是controller? --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.redis.service..*.*(..)))" /> </aop:config> </beans>
applicationContext-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:context="http://www.springframework.org/schema/context" 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.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 自动扫描且只扫描@Controller 扫描的是controller --> <context:component-scan base-package="com.redis.controller" /> <!-- DispatcherServlet是springmvc的入口类 --> <!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 --> <!-- 除了动态资源以后,其他都不拦截(js,css,pictures,font...) --> <mvc:default-servlet-handler /> <!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 --> <mvc:annotation-driven> <mvc:message-converters> <!-- springmvc自带的中文编码转换器 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg index="0" value="UTF-8" /> </bean> <!-- json的格式化 --> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="prettyPrint" value="true" /> </bean> </mvc:message-converters> </mvc:annotation-driven> </beans>
application.properties:
#mysql connector
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
#redis cluster connector
redis.host1=192.168.1.186
redis.port1=6380
redis.host2=192.168.1.186
redis.port2=6381
redis.host3=192.168.1.186
redis.port3=6382
redis.host4=192.168.1.186
redis.port4=6383
redis.host5=192.168.1.186
redis.port5=6384
redis.host6=192.168.1.186
redis.port6=6385
#item key
ITEM_INFO_KEY=ITEM_INFO_KEY
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 首先加载application.properties配置文件 --> <context:property-placeholder location="classpath:application.properties" /> <!-- spring扫描service --> <context:component-scan base-package="com.redis.service" /> <!-- 分离核心配置,把spring和springmvc以及mybatis的配置单独成立一个xml文件,在applicationContext中导入 --> <!-- 导入springmvc配置文件 --> <import resource="springmvc/applicationContext-mvc.xml"/> <!-- 导入jdbc配置文件 --> <import resource="spring/applicationContext-db.xml"/> <!-- 导入事务管理的配置文件 --> <import resource="spring/applicationContext-tx.xml"/> <!-- 导入redis集群的配置信息 --> <import resource="spring/applicationContext-redis.xml"/> </beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app 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" version="3.0"> <!--spring入口文件的配置 --> <!-- 确定配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置spring 监听器,加载xml配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 解决POST请求的中文乱码 --> <filter> <filter-name>CharacterEncodingFilter</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> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- DispatcherServlet:前端控制器 配置前端控制器servlet --> <servlet> <servlet-name>redis_demo</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--加载前端控制器配置文件 上下文配置位置 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc/applicationContext-mvc.xml</param-value> </init-param> <!-- 表示随WEB服务器启动 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>redis_demo</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
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.redis</groupId> <artifactId>redis_demo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>redis_demo Maven Webapp</name> <url>http://maven.apache.org</url> <!-- 统一配置 --> <properties> <!-- junit begin --> <junit.version>4.12</junit.version> <!-- junit end --> <!-- spring begin --> <spring.version>4.3.4.RELEASE</spring.version> <!-- spring end --> <!-- json begin --> <jackson.version>2.8.1</jackson.version> <fastjson.version>1.2.17</fastjson.version> <!-- json end --> <!-- servlet jsp jstl begin --> <servlet-api.version>3.0.1</servlet-api.version> <jsp-api.version>2.0</jsp-api.version> <jstl.version>1.2</jstl.version> <!-- servlet jsp jstl end --> <!-- mysql begin --> <mysql.version>5.1.40</mysql.version> <!-- mysql begin --> <!-- druid begin --> <druid.version>1.0.26</druid.version> <!-- druid end --> <!-- mybatis begin --> <mybatis.version>3.3.0</mybatis.version> <mybatis.spring.version>1.2.3</mybatis.spring.version> <mybatis.paginator.version>1.2.15</mybatis.paginator.version> <mybatis.mapper.version>3.3.9</mybatis.mapper.version> <!-- mybatis end --> <!-- ehcache begin --> <ehcache.version>2.10.3</ehcache.version> <!-- ehcache end --> <!-- redis begin --> <jedis.version>2.9.0</jedis.version> <spring-data-redis.version>1.7.2.RELEASE</spring-data-redis.version> <!-- redis end --> </properties> <dependencies> <!-- 所需要的jar包 --> <!-- junit start --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- junit end --> <!--spring start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</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-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!--spring end --> <!--json start --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!--json end --> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <!-- jsp --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>${jsp-api.version}</version> <scope>provided</scope> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> <scope>runtime</scope> </dependency> <!-- database begin --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!-- database end --> <!-- mybatis plugins begin --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>${mybatis.mapper.version}</version> </dependency> <!-- mybatis plugins end --> <!--ehcache 缓存配置 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> </dependency> <!-- redis begin --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>${jedis.version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>${spring-data-redis.version}</version> </dependency> <!-- redis end --> </dependencies> <build> <finalName>redis_demo</finalName> </build> </project>
RedisDemoController.java:
package com.redis.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.redis.service.IRedisService; import com.redis.service.RedisDemoService; @RestController @RequestMapping("/redis") public class RedisDemoController { @Autowired private RedisDemoService redisDemoService; @Autowired private IRedisService redisService; @RequestMapping(value="/demo",method=RequestMethod.GET) public String demo() { // Map<String, Object> resultMap = new HashMap<String, Object>(); // // 调用service // String result = redisDemoService.demoService(); // if(result != null && "ok".equals(result.toLowerCase())) { // resultMap.put("status", 200); // } else { // resultMap.put("status", 500); // } // return JSONUtil.toJSONString(resultMap); return redisDemoService.findAllItems(redisService); } }
ItemMapper.java:
package com.redis.mapper; import com.redis.model.Item; import tk.mybatis.mapper.common.Mapper; public interface ItemMapper extends Mapper<Item> { }
Item.java:
package com.redis.model; import java.util.Date; import javax.persistence.*; @Table(name = "ego_item") public class Item { /** * 商品id,同时也是商品编号 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** * 商品标题 */ private String title; /** * 商品卖点 */ @Column(name = "sell_point") private String sellPoint; /** * 商品价格,单位为:分 */ private Long price; /** * 库存数量 */ private Integer num; /** * 商品条形码 */ private String barcode; /** * 商品图片 */ private String image; /** * 所属类目,叶子类目 */ private Long cid; /** * 商品状态,1-正常,2-下架,3-删除 */ private Byte status; /** * 创建时间 */ private Date created; /** * 更新时间 */ private Date updated; /** * 获取商品id,同时也是商品编号 * * @return id - 商品id,同时也是商品编号 */ public Long getId() { return id; } /** * 设置商品id,同时也是商品编号 * * @param id 商品id,同时也是商品编号 */ public void setId(Long id) { this.id = id; } /** * 获取商品标题 * * @return title - 商品标题 */ public String getTitle() { return title; } /** * 设置商品标题 * * @param title 商品标题 */ public void setTitle(String title) { this.title = title == null ? null : title.trim(); } /** * 获取商品卖点 * * @return sell_point - 商品卖点 */ public String getSellPoint() { return sellPoint; } /** * 设置商品卖点 * * @param sellPoint 商品卖点 */ public void setSellPoint(String sellPoint) { this.sellPoint = sellPoint == null ? null : sellPoint.trim(); } /** * 获取商品价格,单位为:分 * * @return price - 商品价格,单位为:分 */ public Long getPrice() { return price; } /** * 设置商品价格,单位为:分 * * @param price 商品价格,单位为:分 */ public void setPrice(Long price) { this.price = price; } /** * 获取库存数量 * * @return num - 库存数量 */ public Integer getNum() { return num; } /** * 设置库存数量 * * @param num 库存数量 */ public void setNum(Integer num) { this.num = num; } /** * 获取商品条形码 * * @return barcode - 商品条形码 */ public String getBarcode() { return barcode; } /** * 设置商品条形码 * * @param barcode 商品条形码 */ public void setBarcode(String barcode) { this.barcode = barcode == null ? null : barcode.trim(); } /** * 获取商品图片 * * @return image - 商品图片 */ public String getImage() { return image; } /** * 设置商品图片 * * @param image 商品图片 */ public void setImage(String image) { this.image = image == null ? null : image.trim(); } /** * 获取所属类目,叶子类目 * * @return cid - 所属类目,叶子类目 */ public Long getCid() { return cid; } /** * 设置所属类目,叶子类目 * * @param cid 所属类目,叶子类目 */ public void setCid(Long cid) { this.cid = cid; } /** * 获取商品状态,1-正常,2-下架,3-删除 * * @return status - 商品状态,1-正常,2-下架,3-删除 */ public Byte getStatus() { return status; } /** * 设置商品状态,1-正常,2-下架,3-删除 * * @param status 商品状态,1-正常,2-下架,3-删除 */ public void setStatus(Byte status) { this.status = status; } /** * 获取创建时间 * * @return created - 创建时间 */ public Date getCreated() { return created; } /** * 设置创建时间 * * @param created 创建时间 */ public void setCreated(Date created) { this.created = created; } /** * 获取更新时间 * * @return updated - 更新时间 */ public Date getUpdated() { return updated; } /** * 设置更新时间 * * @param updated 更新时间 */ public void setUpdated(Date updated) { this.updated = updated; } }
RedisServiceImpl.java:
package com.redis.service.impl; import com.redis.service.IRedisService; import redis.clients.jedis.JedisCluster; public class RedisServiceImpl implements IRedisService { private JedisCluster jedisCluster; public void setJedisCluster(JedisCluster jedisCluster) { this.jedisCluster = jedisCluster; } @Override public String set(String key, String value) { return jedisCluster.set(key, value); } @Override public String get(String key) { return jedisCluster.get(key); } @Override public Long hset(String key, String field, String value) { return null; } @Override public String hget(String key, String field) { return null; } @Override public Long del(String... keys) { return null; } @Override public Long hdel(String key, String... fields) { return null; } @Override public Boolean exists(String key) { return null; } @Override public Long expire(String key, int seconds) { return null; } @Override public Long ttl(String key) { return null; } @Override public Long incr(String key) { return null; } }
IRedisService.java:
package com.redis.service; public interface IRedisService { /** * 设置指定 key 的值 * * @param key * @param value * @return */ String set(String key, String value); /** * 获取指定 key 的值 * * @param key * @return */ String get(String key); /** * 设置存储在哈希表中指定字段的值 * * @param key * @param field * @param value * @return */ Long hset(String key, String field, String value); /** * 获取存储在哈希表中指定字段的值 * * @param key * @param field * @return */ String hget(String key, String field); /** * 删除 key和对应的值 * * @param keys * @return */ Long del(String... keys); /** * 删除key的哈希表字段 * * @param key * @param fields * @return */ Long hdel(String key, String... fields); /** * 检查给定 key 是否存在 * * @param key * @return */ Boolean exists(String key); /** * 为给定 key 设置过期时间 * * @param key * @param seconds * @return */ Long expire(String key, int seconds); /** * 以秒为单位返回 key 的剩余过期时间 * * @param key * @return */ Long ttl(String key); /** * 自增 * @param key * @return */ Long incr(String key); }
RedisDemoService.java:
package com.redis.service; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.redis.mapper.ItemMapper; import com.redis.utils.JSONUtil; @Service public class RedisDemoService { @Value("${ITEM_INFO_KEY}") private String itemInfoKey; @Autowired private ItemMapper itemMapper; // @Autowired // private IRedisService redisService; public String demoService() { String itemJson = JSONUtil.toJSONString(itemMapper.selectAll()); String result = null; if(itemJson.isEmpty()) { return result; } //result = redisService.set(itemInfoKey, itemJson);// 如果存储生成,返回OK return result; } // findAllItems这个方法需要向前端项目传递商品数据 public String findAllItems(IRedisService redisService) { // 如果缓存中已经有itemInfoKey的数据了,直接就从缓存中取,不再查询数据库,而且也不需要存入redis Map<Integer, Object> resultMap = new HashMap<Integer, Object>(); String itemJsons = ""; // 从redis数据库中查询数据 itemJsons = redisService.get(itemInfoKey); // 如果redis中没有该数据 if(itemJsons.isEmpty()) { // 从mysql中查询出需要的数据 itemJsons = JSONUtil.toJSONString(itemMapper.selectAll()); // 存入redis集群中 String result = redisService.set(itemInfoKey, itemJsons); if("ok".equals(result.toLowerCase())) { resultMap.put(200, itemJsons); } else { resultMap.put(500, null); } } else { resultMap.put(200, itemJsons); } return JSONUtil.toJSONString(resultMap); } }
JSONUtil.java:
package com.redis.utils; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; public class JSONUtil { // 定义jackson对象 private static final ObjectMapper mapper = new ObjectMapper(); /** * 将对象转换成json字符串 * @param data * @return */ public static String toJSONString(Object data) { try { String string = mapper.writeValueAsString(data); return string; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } /** * 将json结果集转化为对象 * @param jsonData * @param beanType * @return */ public static <T> T parseObject(String jsonData, Class<T> beanType) { try { T t = mapper.readValue(jsonData, beanType); return t; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 将json数据转换成list * @param jsonData * @param beanType * @return */ public static <T> List<T> parseArray(String jsonData, Class<T> beanType) { JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, beanType); try { List<T> list = mapper.readValue(jsonData, javaType); return list; } catch (Exception e) { e.printStackTrace(); } return null; } }
2.实体类mapper生成器(generator):
generatorConfig.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <properties resource="jdbc.properties" /> <context id="mysql" targetRuntime="MyBatis3Simple"> <!-- 使用mybatis的通用mapper插件 --> <plugin type="${mapper.plugin}"> <property name="mappers" value="${mapper.Mapper}" /> </plugin> <commentGenerator> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--数据库连接的信息:驱动类、连接地址、用户名、密码 --> <jdbcConnection driverClass="${jdbc.driverClassName}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- targetProject:生成pojo的位置 targetPackage:把生成的pojo放在指定包中 --> <javaModelGenerator targetPackage="cn.solr.model" targetProject="./src/main/java"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- targetProject:mapper映射文件生成的位置 mapper.xml文件生成出来的位置,放在mapper文件夹在,mapper文件夹会在./src/main/resources生成 --> <sqlMapGenerator targetPackage="mapper" targetProject="./src/main/resources"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:mapper接口生成的位置 XXXMapper.java(I)生成出来的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.solr.mapper" targetProject="./src/main/java"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- !!!!! <table>指向数据库 从数据库中读取表信息并生成对应的实体类 tableName:是数据库中的表名,必须要和数据库中一致(包括大小写和下划线。。。) domainObjectName:根据表信息生成的pojo的名字(xxx.java) --> <table tableName="ego_item" domainObjectName="Item"> <!-- generatedKey:主键自增生成策略 column:指定主键的列 sqlStatement:指定数据库类型 identity:mysql的自增主键 --> <generatedKey column="id" sqlStatement="Mysql" identity="true" /> </table> <table tableName="ego_item_desc"> <generatedKey column="id" sqlStatement="Mysql" identity="true"/> </table> <table tableName="ego_item_cat" domainObjectName="ego_content_category" > <generatedKey column="id" sqlStatement="Mysql" identity="true"/> </table> </context> </generatorConfiguration>
jdbc.properties:
#\u6570\u636e\u5e93\u8fde\u63a5\u4fe1\u606f
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
mapper.plugin=tk.mybatis.mapper.generator.MapperPlugin
mapper.Mapper=tk.mybatis.mapper.common.Mapper
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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ego-generator</groupId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ego-generator Maven Webapp</name> <url>http://maven.apache.org</url> <artifactId>ego-generator</artifactId> <dependencies> <!-- mybatis begin --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <!-- mybatis end --> <!-- mybatis generator begin --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> <scope>compile</scope> <optional>true</optional> </dependency> <!-- mybatis generator end --> <!-- mybatis plugins begin 通用的mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.4.3</version> </dependency> <!-- mybatis plugins end --> </dependencies> <build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <!-- 该插件的核心配置(在项目进入编译期的时候,会加载<configuration>标签下的配置文件) --> <configuration> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.3.9</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>
右键pom.xml文件,Run as: mybatis-generator.generate,生成对应实体类和mapper