赞
踩
项目目录:
application.yml
- spring:
- datasource:
- url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
- username: root
- password: root
- driver-class-name: com.mysql.jdbc.Driver
- test-while-idle: true
- test-on-borrow: true
- validation-query: SELECT 1 FROM DUAL
- time-between-eviction-runs-millis: 300000
- min-evictable-idle-time-millis: 1800000
- freemarker:
- charset: UTF-8
- cache: false
- expose-request-attributes: false
- request-context-attribute: request
- expose-session-attributes: false
- content-type: text/html
- template-loader-path: classpath:/templates
- suffix: .ftl
- check-template-location: true
- redis:
- database: 1
- host: 127.0.0.1
- port: 6379
- jedis:
- pool:
- max-active: 8
- max-wait: -1
- max-idle: 8
- min-idle: 0
- timeout: 10000
pom:
- <dependencies>
- <!-- sprinboot web -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>1.1.1</version>
- </dependency>
- <!-- mysql 依赖 -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
- <!-- 引入freemarker包 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-freemarker</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- </dependency>
- <dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- <version>2.6</version>
- </dependency>
-
- <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
- <dependency>
- <groupId>redis.clients</groupId>
- <artifactId>jedis</artifactId>
- <version>3.0.1</version>
- </dependency>
-
- </dependencies>
MybatisRedisCache类:
- import com.mayikt.api.utils.SerializeUtil;
- import org.apache.ibatis.cache.Cache;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import redis.clients.jedis.Jedis;
- import redis.clients.jedis.JedisPool;
- import java.util.concurrent.locks.ReadWriteLock;
- import java.util.concurrent.locks.ReentrantReadWriteLock;
-
- /**
- * mybatis二级缓存整合Redis
- */
- public class MybatisRedisCache implements Cache {
- private static Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class);
-
- private Jedis redisClient = createReids();
-
- private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
-
- private String id;
-
- public MybatisRedisCache(final String id) {
- if (id == null) {
- throw new IllegalArgumentException("Cache instances require an ID");
- }
- logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id=" + id);
- this.id = id;
- }
-
-
- public String getId() {
- return this.id;
- }
-
-
- public int getSize() {
-
- return Integer.valueOf(redisClient.dbSize().toString());
- }
-
-
- public void putObject(Object key, Object value) {
- logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:" + key + "=" + value);
- redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));
- }
-
- public Object getObject(Object key) {
- Object value = SerializeUtil.unserialize(redisClient.get(SerializeUtil.serialize(key.toString())));
- logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:" + key + "=" + value);
- return value;
- }
-
-
- public Object removeObject(Object key) {
- return redisClient.expire(SerializeUtil.serialize(key.toString()), 0);
- }
-
-
- public void clear() {
- redisClient.flushDB();
- }
-
-
- public ReadWriteLock getReadWriteLock() {
- return readWriteLock;
- }
-
- protected static Jedis createReids() {
- JedisPool pool = new JedisPool("127.0.0.1", 6379);
- return pool.getResource();
- }
- }
entity:
- public class OrderEntity implements Serializable {
-
- private int id;
- private String orderName;
- private String orderDes;
-
- /**
- * @return the id
- */
- public int getId() {
- return id;
- }
-
- /**
- * @param id
- * the id to set
- */
- public void setId(int id) {
- this.id = id;
- }
-
- /**
- * @return the orderName
- */
- public String getOrderName() {
- return orderName;
- }
-
- /**
- * @param orderName
- * the orderName to set
- */
- public void setOrderName(String orderName) {
- this.orderName = orderName;
- }
-
- /**
- * @return the orderDes
- */
- public String getOrderDes() {
- return orderDes;
- }
-
- /**
- * @param orderDes
- * the orderDes to set
- */
- public void setOrderDes(String orderDes) {
- this.orderDes = orderDes;
- }
-
- }
mapper:
- import com.mayikt.api.cache.MybatisRedisCache;
- import com.mayikt.api.entity.OrderEntity;
- import org.apache.ibatis.annotations.CacheNamespace;
- import org.apache.ibatis.annotations.Insert;
- import org.apache.ibatis.annotations.Select;
-
- import java.util.List;
-
-
- @CacheNamespace(implementation = MybatisRedisCache.class)
- public interface OrderMapper {
- @Insert("insert order_info values (null,#{orderName},#{orderDes})")
- public int addOrder(OrderEntity OrderEntity);
-
- @Select("SELECT * FROM order_info;")
- public List<OrderEntity> findByOrder();
- }
-
RedisToken:
- import org.apache.commons.lang.StringUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.StringRedisTemplate;
- import org.springframework.stereotype.Component;
-
- import java.util.UUID;
- import java.util.concurrent.TimeUnit;
-
- @Component
- public class RedisToken {
- @Autowired
- private StringRedisTemplate stringRedisTemplate;
-
- /**
- * 获取Token
- *
- * @return
- */
- public String getToken() {
- //1. 使用uuid生成Token
- String token = UUID.randomUUID().toString().replace("-", "");
- //2. 将Token存放到Redis中
- setString(token, token, 7200l);
- return token;
- }
-
- public Boolean findByToken(String token) {
- if (StringUtils.isEmpty(token)) {
- return false;
- }
- String redisToken = getString(token);
- if(StringUtils.isEmpty(redisToken)){
- return false;
- }
- delKey(redisToken);
- return true;
- }
-
-
- private void setString(String key, Object data, Long timeout) {
- if (data instanceof String) {
- String value = (String) data;
- stringRedisTemplate.opsForValue().set(key, value);
- }
- if (timeout != null) {
- stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
- }
- }
-
- private String getString(String key) {
- return stringRedisTemplate.opsForValue().get(key);
- }
-
- private void delKey(String key) {
- stringRedisTemplate.delete(key);
- }
-
- }
Conroller:
- @Controller
- public class ApiOrderService {
- @Autowired
- private OrderMapper orderMapper;
- @Autowired
- private RedisToken redisToken;
-
- // @RequestMapping("/addOrder")
- // public String addOrder(OrderEntity orderEntity) {
- // int reuslt = orderMapper.addOrder(orderEntity);
- // return reuslt > 0 ? "success" : "fail";
- // }
- @RequestMapping("/")
- public String index(HttpServletRequest request) {
- // 1.页面中存放该Token
- String token = redisToken.getToken();
- request.setAttribute("token", token);
- return "index";
- }
-
- @RequestMapping("/addOrder")
- public String addOrder(OrderEntity orderEntity, String token) {
- Boolean isToken = redisToken.findByToken(token);
- if (!isToken) {
- return "repeat";
- }
- int result = orderMapper.addOrder(orderEntity);
- return result > 0 ? "success" : "fail";
- }
-
- @RequestMapping("/getOrderList")
- @ResponseBody
- public Object getOrderList() {
- return orderMapper.findByOrder();
- }
- }
SerializeUtil:
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
-
- public class SerializeUtil {
- 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;
- }
- }
认准蚂蚁课堂:http://www.mayikt.com/ 很多免费有用干货
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。