Springboot Redis Mybatis

Springboot Redis Mybatis

0.

  • SpringBoot2.3.x
  • Mybatis3.x
  • Redis5.x
  • redis redis5.x
  • IDEA2020.x Eclipse2020

1. springboot IDEA ( )

IDEA2020 springboot2.3.x

1

SpringBoot :

-Property 'configuration' and 'configLocation' can not specified with together

yaml mybatis

SSM mybatis-comfig.xml

springboot

application.yaml configuration config-location configuration config-location !

  • SpringBoot mybatis mybatis mybatis-config application.yaml

2

@EnableAutoConfiguration

IDEA

@EnableAutoConfiguration

@EnableAutoConfiguration

(idea ALT+ENTER )

OK

2. SpringBoot Redis Mybatis

mybatis/?

MyBatis

  • sqlSession sql

2.1 SQL

CREATE TABLE `score_flow` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT ' id', `score` bigint(19) unsigned NOT NULL COMMENT ' ', `user_id` int(11) unsigned NOT NULL COMMENT ' id', `user_name` varchar(30) NOT NULL DEFAULT '' COMMENT ' ', PRIMARY KEY (`id`), KEY `idx_userid` (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4; CREATE TABLE `sys_user` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `user_name` varchar(11) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT ' ', `image` varchar(11) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT ' ', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; CREATE TABLE `user_score` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT ' ', `user_id` int(11) unsigned NOT NULL COMMENT ' ID', `user_score` bigint(19) unsigned NOT NULL COMMENT ' ', `name` varchar(30) NOT NULL DEFAULT '' COMMENT ' ', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

2.2 Springboot application.yaml

# server: port: 8080 # servlet: context-path: /demo #===================================== ===================================== spring: #=====================================Redis========================================= redis: # Redis 0 database: 0 # Redis host: 8.XXXXXX.136 # Redis port: 6379 # Redis password: cspXXXXXX29 jedis: pool: # max-active: 8 # max-wait: -1 # max-idle: 8 # min-idle: 0 # timeout: 8000 #=====================================Mysql========================================= datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/test2?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC username: root password: root type: com.alibaba.druid.pool.DruidDataSource # minIdle: 5 maxActive: 100 initialSize: 10 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 50 removeAbandoned: true filters: stat # ,wall,log4j # filters sql 'wall' connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # connectProperties mergeSql SQL useGlobalDataSourceStat: true # DruidDataSource druidLoginName: wjf # druid druidPassword: wjf # druid cachePrepStmts: true # # sql mybatis: # mapper mapper-locations: com.haust.redisdemo.mapper/*.xml # type-aliases-package: com.haust.redisdemo.domain # mybatis config-location: classpath:/mybatis-config.xml

2.3 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> <settings> <!-- sql --> <setting name="logImpl" value="STDOUT_LOGGING"/> <!-- --> <setting name="cacheEnabled" value="true"/> <!-- --> <setting name="lazyLoadingEnabled" value="true"/> <!-- --> <setting name="aggressiveLazyLoading" value="true"/> <!-- sql ( ) default:true --> <setting name="multipleResultSetsEnabled" value="true"/> <!-- ( ) default:true --> <setting name="useColumnLabel" value="true"/> <!-- JDBC true default:false --> <setting name="useGeneratedKeys" value="false"/> <!-- MyBatis NONE PARTIAL: FULL: --> <setting name="autoMappingBehavior" value="PARTIAL"/> <!-- SIMPLE: REUSE: prepared statements BATCH: --> <setting name="defaultExecutorType" value="SIMPLE"/> <!-- --> <setting name="defaultStatementTimeout" value="25"/> <!-- fetchSize --> <setting name="defaultFetchSize" value="100"/> <!-- RowBounds false --> <setting name="safeRowBoundsEnabled" value="false"/> <!-- --> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- session: statement: ( ) defalut:session --> <setting name="localCacheScope" value="SESSION"/> <!-- OTHER, oracle null NULL --> <setting name="jdbcTypeForNull" value="NULL"/> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/> </settings> </configuration>

2.4

@SpringBootApplication @EnableAutoConfiguration @MapperScan("com.haust.redisdemo.mapper") public class XdRedisDemoApplication { public static void main(String[] args) { SpringApplication.run(XdRedisDemoApplication.class, args); } }

2.5 User

@Data @AllArgsConstructor @NoArgsConstructor @Accessors(chain = true) /** * */ public class User implements Serializable {// /** * */ private static final long serialVersionUID = -4415438719697624729L; /** * id */ private String id; /** * */ private String userName; }

2.6 UserMapper.java UserMapper.xml

/** * @Auther: csp1999 * @Date: 2020/11/17/10:36 * @Description: UserMapper */ @Repository public interface UserMapper { void insert(User user); void update(User user); void delete(@Param("id") String id); User find(@Param("id") String id); List<User> query(@Param("userName") String userName); void deleteAll(); }
<?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.haust.redisdemo.mapper.UserMapper"> <select id="query" resultType="com.haust.redisdemo.domain.User"> select id ,user_name from sys_user where 1=1 <if test="userName != null"> and user_name like CONCAT('%',#{userName},'%') </if> </select> <insert id="insert" parameterType="com.haust.redisdemo.domain.User"> insert sys_user(id,user_name) values(#{id},#{userName}) </insert> <update id="update" parameterType="com.haust.redisdemo.domain.User"> update sys_user set user_name = #{userName} where id=#{id} </update> <delete id="delete" parameterType="string"> delete from sys_user where id= #{id} </delete> <select id="find" resultType="com.haust.redisdemo.domain.User" parameterType="string"> select id,user_name from sys_user where id=#{id} </select> <delete id="deleteAll"> delete from sys_user </delete> </mapper>

2.7 redis

redis RedisTemplete RedisTemplete

/** * @Auther: csp1999 * @Date: 2020/11/17/10:08 * @Description: redis */ @Component public class RedisUtil { @Autowired private RedisTemplate redisTemplate; private static double size = Math.pow(2, 32); /** * * * @param key * @param offset 8Bit=1Byte * @return */ public boolean setBit(String key, long offset, boolean isShow) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.setBit(key, offset, isShow); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * * * @param key * @param offset * @return */ public boolean getBit(String key, long offset) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.getBit(key, offset); } catch (Exception e) { e.printStackTrace(); } return result; } /** * * * @param key * @param value * @return */ public boolean set(final String key, Object value) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * * * @param key * @param value * @return */ public boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * value * * @param keys */ public void remove(final String... keys) { for (String key : keys) { remove(key); } } /** * value * * @param key */ public void remove(final String key) { if (exists(key)) { redisTemplate.delete(key); } } /** * value * * @param key * @return */ public boolean exists(final String key) { return redisTemplate.hasKey(key); } /** * * * @param key * @return */ public Object get(final String key) { Object result = null; ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.get(key); return result; } /** * * * @param key * @param hashKey * @param value */ public void hmSet(String key, Object hashKey, Object value) { HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); hash.put(key, hashKey, value); } /** * * * @param key * @param hashKey * @return */ public Object hmGet(String key, Object hashKey) { HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); return hash.get(key, hashKey); } /** * * * @param k * @param v */ public void lPush(String k, Object v) { ListOperations<String, Object> list = redisTemplate.opsForList(); list.rightPush(k, v); } /** * * * @param k * @param l * @param l1 * @return */ public List<Object> lRange(String k, long l, long l1) { ListOperations<String, Object> list = redisTemplate.opsForList(); return list.range(k, l, l1); } /** * * * @param key * @param value */ public void add(String key, Object value) { SetOperations<String, Object> set = redisTemplate.opsForSet(); set.add(key, value); } /** * * * @param key * @return */ public Set<Object> setMembers(String key) { SetOperations<String, Object> set = redisTemplate.opsForSet(); return set.members(key); } /** * * * @param key * @param value * @param scoure */ public void zAdd(String key, Object value, double scoure) { ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); zset.add(key, value, scoure); } /** * * * @param key * @param scoure * @param scoure1 * @return */ public Set<Object> rangeByScore(String key, double scoure, double scoure1) { ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); redisTemplate.opsForValue(); return zset.rangeByScore(key, scoure, scoure1); } //redis public void saveDataToRedis(String name) { double index = Math.abs(name.hashCode() % size); long indexLong = new Double(index).longValue(); boolean availableUsers = setBit("availableUsers", indexLong, true); } //redis public boolean getDataToRedis(String name) { double index = Math.abs(name.hashCode() % size); long indexLong = new Double(index).longValue(); return getBit("availableUsers", indexLong); } /** * * * @param key * @param value */ public Long zRank(String key, Object value) { ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); return zset.rank(key, value); } /** * * * @param key */ public Set<ZSetOperations.TypedTuple<Object>> zRankWithScore(String key, long start, long end) { ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); Set<ZSetOperations.TypedTuple<Object>> ret = zset.rangeWithScores(key, start, end); return ret; } /** * * * @param key * @param value */ public Double zSetScore(String key, Object value) { ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); return zset.score(key, value); } /** * * * @param key * @param value * @param scoure */ public void incrementScore(String key, Object value, double scoure) { ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); zset.incrementScore(key, value, scoure); } /** * * * @param key */ public Set<ZSetOperations.TypedTuple<Object>> reverseZRankWithScore(String key, long start, long end) { ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); Set<ZSetOperations.TypedTuple<Object>> ret = zset.reverseRangeByScoreWithScores(key, start, end); return ret; } /** * * * @param key */ public Set<ZSetOperations.TypedTuple<Object>> reverseZRankWithRank(String key, long start, long end) { ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); Set<ZSetOperations.TypedTuple<Object>> ret = zset.reverseRangeWithScores(key, start, end); return ret; } }

RedisConfig RedisTemplate IOC

/** * @Auther: csp1999 * @Date: 2020/11/14/18:44 * @Description: Redis */ @Configuration //@EnableCaching// public class RedisConfig { /** * redisTemplate IOC * * @param factory * @return */ @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, String> redisTemplate = new RedisTemplate<>(); //RedisTemplate RedisConnectionFactory redisTemplate.setConnectionFactory(factory); return redisTemplate; } }

2.8 UserController redis

/** * @Auther: csp1999 * @Date: 2020/11/17/11:38 * @Description: */ @RestController public class UserController { /** * key */ private static final String key = "userCache_"; @Resource private UserMapper userMapper; @Resource private RedisUtil redisUtil; /** * id : * redis ( ) * set get * * @param id * @return */ @RequestMapping("/getUserCache") public User getUseCache(String id) { //step1: redis User user = (User) redisUtil.get(key + id); //step2: DB if (user == null) { User userDB = userMapper.find(id); System.out.println("fresh value from DB id:" + id); //step3: DB redis if (userDB != null) { redisUtil.set(key + id, userDB); return userDB; } } return user; } }

( )

id user redis user

http://localhost:8080/demo/getExpire?id=1

sql user redis user

redis mysql MySQL redis

springboot redis

  • 1 springboot cache redis ehcache

    • @CacheConfig(cacheNames= userInfoCache ) redis
    • @Cacheable( ) -
    • @CachePut( ) @CachePut @CachePut
    • @CacheEvict( )
  • 2 springboot cache

    • 1 pom.xml

      <!-- springboot cache --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
    • 2 RedisConfig @EnableCaching

      @Configuration @EnableCaching // public class RedisConfig {
    • 3 SpEL spring el

    UserService.java

    /** * User */ @Service // userInfoCache @CacheConfig(cacheNames = "userInfoCache") // @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class) public class UserService { @Autowired private UserMapper userMapper; /** * * * * <p> * * * @param user * @return */ //#p0 redis key // #p1 redis key... 1 user //#p0.id user id redis key @CachePut(key = "#p0.id") // public User insertUser(User user) { userMapper.insert(user); //user id return userMapper.find(user.getId()); } /** * @CachePut * * * @param user * @return */ @CachePut(key = "#p0.id") public User updateUser(User user) { userMapper.update(user); // return userMapper.find(user.getId()); } /** * @Cacheable * <p> * springboot cache * * @param id * @return */ @Nullable// NULL @Nullable @Nonnull @Cacheable(key = "#p0") public User findById(String id) { System.err.println(" id=" + id + " "); Assert.notNull(id, "id "); return userMapper.find(id); } /** * userInfoCache,key id * * * @param id */ @CacheEvict(key = "#p0") public void deleteById(String id) { userMapper.delete(id); } /** * userInfoCache ) * */ @CacheEvict(allEntries = true) public void deleteAll() { userMapper.deleteAll(); } }

    UserController UserService redis :

    /** * id * * userService springboot cache * @param id * @return */ @RequestMapping("/getByCache") public User getByCache(String id) { User user = userService.findById(id); return user; }

springboot cache

  • key userCache::3
  • ( )
  • JDKSerialazable

springboot cache

1) KeyGenerator springboot cache key userCache::3

2) cacheManager springboot cache

3 Jackson Gson( jackson ) springboot cache JDKSerialazable boot

1. RedisConfig

/** * KeyGenerator springboot cache key , * * @return */ @Bean public KeyGenerator simpleKeyGenerator() { return (o, method, objects) -> {//o: method: objects: /** * ( ) KeyGenerator * + + * eg: UserInfoList::UserService.findByIdTtl[1] * * JVM */ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(o.getClass().getSimpleName()); stringBuilder.append("."); stringBuilder.append(method.getName()); stringBuilder.append("["); for (Object obj : objects) { stringBuilder.append(obj.toString()); } stringBuilder.append("]"); return stringBuilder.toString(); }; } /** * * * @param redisConnectionFactory * @return */ @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { return new RedisCacheManager( RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), // key 600s this.getRedisCacheConfigurationWithTtl(600), // key key this.getRedisCacheConfigurationMap() ); } // key Map: key: value: private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() { Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>(); //key UserInfoList 100s redisCacheConfigurationMap.put("UserInfoList", this.getRedisCacheConfigurationWithTtl(100)); //key UserInfoListAnother 18000s == 5h redisCacheConfigurationMap.put("UserInfoListAnother", this.getRedisCacheConfigurationWithTtl(18000)); return redisCacheConfigurationMap; } // jackson private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) { Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith( RedisSerializationContext .SerializationPair .fromSerializer(jackson2JsonRedisSerializer) ).entryTtl(Duration.ofSeconds(seconds)); return redisCacheConfiguration; }

UserService.java

/** * @Cacheable * <p> * springboot cache * * @param id * @return */ @Nullable @Cacheable(value = "UserInfoList", keyGenerator = "simpleKeyGenerator") public User findByIdTtl(String id) { // System.err.println(" id=" + id + " "); Assert.notNull(id, "id "); return userMapper.find(id); }

controller

/** * id * springboot cache * * key UserInfoList::UserService.findByIdTtl[1] * jackson * @param id * @return */ @RequestMapping(value = "/getExpire", method = RequestMethod.GET) public User findByIdTtl(String id) { User user = new User(); try { user = userService.findByIdTtl(id); } catch (Exception e) { System.err.println(e.getMessage()); } return user; }

/redis key

redis key

redis

3. : redis

2018

  • 1

    • CPU
  • 2

    • 1 key whiltList value 1000w uid setNx whiltList value nullValue mutex Redis SETNX set mutex key load db get
    • 2 ! ! reload key
    • 3 C1 C2 C1 C2 C1 C2
    • 4
    • 5

2018

  • 1

    • key value ( )
  • 2

    • 1 ( )
    • 2 BloomFilter bit bitmap bitmap

2018 redis

  • 1 1 redis

    • 1
    • 2 key setex set expire
    • 3 rdb aof
    • 4 redis redis cluster
  • 2 2 redis

    • 1 sorted Set
    • 2 key springboot cache
    • 3 redis seesion
    • 4
    • 5 redis
    • 6 redis

~