案例一
- demo为
chnx/springboot/redis01
- 创建springboot项目,导入redis依赖
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-data-redis</artifactId> |
| </dependency> |
| |
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-data-redis</artifactId> |
| </dependency> |
| |
| spring: |
| redis: |
| database: 0 |
| host: 127.0.0.1 |
| port: 6379 |
| password: 123456 |
| jedis: |
| pool: |
| max-active: 100 |
| max-idle: 10 |
| max-wait: 100000 |
| timeout: 5000 |
| |
| @SpringBootTest |
| class Redis01ApplicationTests { |
| |
| @Autowired |
| StringRedisTemplate redisTemplate; |
| |
| |
| |
| |
| |
| @Test |
| void testRedis(){ |
| ValueOperations<String, String> operations = redisTemplate.opsForValue(); |
| operations.set("hello","world"); |
| String hello = operations.get("hello"); |
| System.out.println(hello); |
| } |
| } |
| |
| package com.chnq.redis01.controller; |
| |
| import com.chnq.redis01.entity.User; |
| import org.springframework.beans.factory.annotation.Autowired; |
| import org.springframework.data.redis.core.RedisTemplate; |
| import org.springframework.data.redis.core.ValueOperations; |
| import org.springframework.web.bind.annotation.RequestBody; |
| import org.springframework.web.bind.annotation.RequestMapping; |
| import org.springframework.web.bind.annotation.RequestMethod; |
| import org.springframework.web.bind.annotation.RestController; |
| |
| @RestController |
| @RequestMapping("/test") |
| public class JedisController { |
| |
| @Autowired |
| RedisTemplate redisTemplate; |
| |
| @RequestMapping("/str") |
| public String testStr1(){ |
| ValueOperations<String, String> operations = redisTemplate.opsForValue(); |
| operations.set("username","goudan"); |
| String name = operations.get("username"); |
| System.out.println(name); |
| return name; |
| } |
| |
| @RequestMapping(value = "/str1", method = RequestMethod.POST) |
| public String listAll(@RequestBody User user){ |
| ValueOperations<String, String> operations = redisTemplate.opsForValue(); |
| operations.set("name", user.getName()); |
| operations.append("name", user.getAge()); |
| String name = operations.get("name"); |
| System.out.println(name); |
| return "success"; |
| } |
| |
| } |
| |
案例二
- demo为
chnx/springboot/redis01
在案例一的基础上,使用lettuce操作redis
- 参考
- pom.xml
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-data-redis</artifactId> |
| </dependency> |
| |
| |
| |
| |
| |
| |
| |
| spring: |
| redis: |
| database: 0 |
| host: 192.168.96.192 |
| port: 6379 |
| password: 123456 |
| client-type: lettuce |
| lettuce: |
| pool: |
| max-active: 8 |
| max-wait: -1ms |
| max-idle: 8 |
| min-idle: 0 |
| timeout: 2000 |
| |
| import org.springframework.context.annotation.Bean; |
| import org.springframework.context.annotation.Configuration; |
| import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; |
| import org.springframework.data.redis.core.RedisTemplate; |
| import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; |
| import org.springframework.data.redis.serializer.StringRedisSerializer; |
| import java.io.Serializable; |
| |
| @Configuration |
| public class LettuceRedisConfig { |
| |
| @Bean |
| public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) { |
| RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>(); |
| redisTemplate.setKeySerializer(new StringRedisSerializer()); |
| redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); |
| redisTemplate.setConnectionFactory(connectionFactory); |
| return redisTemplate; |
| } |
| |
| } |
| |
| import org.springframework.data.redis.core.RedisTemplate; |
| import org.springframework.stereotype.Component; |
| import javax.annotation.Resource; |
| import java.util.concurrent.TimeUnit; |
| |
| @Component |
| public class RedisUtils { |
| |
| @Resource |
| private RedisTemplate<String, String> redisTemplate; |
| |
| |
| |
| |
| |
| |
| public void set(String key, String value) { |
| redisTemplate.opsForValue().set(key, value); |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| public void set(String key, String value, long timeout, TimeUnit unit) { |
| redisTemplate.opsForValue().set(key, value, timeout, unit); |
| } |
| |
| |
| |
| |
| |
| |
| public void expire(String key, long time) { |
| redisTemplate.expire(key, time, TimeUnit.SECONDS); |
| } |
| |
| |
| |
| |
| |
| |
| public String get(String key) { |
| return String.valueOf(redisTemplate.opsForValue().get(key)); |
| } |
| |
| |
| |
| |
| |
| |
| public boolean delete(String key) { |
| return redisTemplate.delete(key); |
| } |
| |
| } |
| |
| @SpringBootTest |
| public class LettuceTest { |
| |
| @Resource |
| private RedisTemplate<String, String> redisTemplate; |
| |
| @Test |
| void testRedis(){ |
| ValueOperations<String, String> operations = redisTemplate.opsForValue(); |
| operations.set("hello","world"); |
| String hello = operations.get("hello"); |
| System.out.println(hello); |
| } |
| } |
| |
| import com.chnq.redis01.entity.User; |
| import com.chnq.redis01.utils.RedisUtils; |
| import org.springframework.web.bind.annotation.RequestBody; |
| import org.springframework.web.bind.annotation.RequestMapping; |
| import org.springframework.web.bind.annotation.RequestMethod; |
| import org.springframework.web.bind.annotation.RestController; |
| import javax.annotation.Resource; |
| |
| @RestController |
| @RequestMapping("/test1") |
| public class LettuceController { |
| |
| |
| @Resource |
| private RedisUtils redisUtils; |
| |
| @RequestMapping(value = "/str1", method = RequestMethod.POST) |
| public String listAll(@RequestBody User user){ |
| String name = user.getName(); |
| String age = user.getAge(); |
| redisUtils.set(name, age); |
| return "success"; |
| } |
| |
| } |
| |
案例三
- demo为
chenx/jedis_redisdemo
- 参考
- 创建maven工程
- 引入依赖
| <dependency> |
| <groupId>redis.clients</groupId> |
| <artifactId>jedis</artifactId> |
| <version>3.2.0</version> |
| </dependency> |
| |
| package com.atguigu.jedis; |
| |
| import org.junit.Test; |
| import redis.clients.jedis.Jedis; |
| import java.util.HashMap; |
| import java.util.List; |
| import java.util.Map; |
| import java.util.Set; |
| |
| public class JedisDemo1 { |
| |
| |
| |
| |
| public static void main(String[] args) { |
| |
| Jedis jedis = new Jedis("192.168.0.102",6379); |
| |
| String value = jedis.ping(); |
| System.out.println(value); |
| jedis.close(); |
| } |
| |
| |
| |
| |
| |
| @Test |
| public void demo5() { |
| |
| Jedis jedis = new Jedis("192.168.0.102",6379); |
| |
| jedis.zadd("zset01",100d,"shanghai"); |
| jedis.zadd("zset01", 90d, "l4"); |
| jedis.zadd("zset01", 80d, "w5"); |
| jedis.zadd("zset01", 70d, "z6"); |
| |
| Set<String> china = jedis.zrange("zset01", 0, 3); |
| for (String e : china) { |
| System.out.println(e); |
| } |
| |
| jedis.close(); |
| } |
| |
| |
| @Test |
| public void demo4() { |
| |
| Jedis jedis = new Jedis("192.168.0.102",6379); |
| |
| jedis.hset("hash1","userName","lisi"); |
| System.out.println(jedis.hget("hash1","userName")); |
| |
| Map<String,String> map = new HashMap<String,String>(); |
| map.put("telphone","13810169999"); |
| map.put("address","atguigu"); |
| map.put("email","abc@163.com"); |
| jedis.hmset("hash2",map); |
| List<String> result = jedis.hmget("hash2", "telphone","email"); |
| for (String element : result) { |
| System.out.println(element); |
| } |
| jedis.close(); |
| } |
| |
| |
| @Test |
| public void demo3() { |
| |
| Jedis jedis = new Jedis("192.168.0.102",6379); |
| |
| jedis.sadd("names","lucy"); |
| jedis.sadd("names","mary"); |
| Set<String> names = jedis.smembers("names"); |
| System.out.println(names); |
| |
| jedis.sadd("orders", "order02"); |
| jedis.sadd("orders", "order03"); |
| jedis.sadd("orders", "order04"); |
| Set<String> smembers = jedis.smembers("orders"); |
| for (String order : smembers) { |
| System.out.println(order); |
| } |
| |
| jedis.srem("orders", "order02"); |
| jedis.close(); |
| } |
| |
| |
| @Test |
| public void demo2() { |
| |
| Jedis jedis = new Jedis("192.168.0.102",6379); |
| |
| jedis.lpush("key1","lucy","mary","jack"); |
| List<String> values = jedis.lrange("key1", 0, -1); |
| System.out.println(values); |
| jedis.close(); |
| } |
| |
| |
| @Test |
| public void demo1() { |
| |
| Jedis jedis = new Jedis("192.168.0.102",6379); |
| |
| jedis.set("name","lucy"); |
| |
| String name = jedis.get("name"); |
| System.out.println(name); |
| |
| jedis.mset("k1","v1","k2","v2"); |
| List<String> mget = jedis.mget("k1", "k2"); |
| System.out.println(mget); |
| |
| Set<String> keys = jedis.keys("*"); |
| for(String key : keys) { |
| System.out.println(key); |
| } |
| jedis.close(); |
| } |
| |
| } |
| |
案例四
- demo为
chenx/redis_springboot
- 参考
- 创建springboot项目,导入所需依赖
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-data-redis</artifactId> |
| </dependency> |
| |
案例五
| <dependencies> |
| <dependency> |
| <groupId>io.lettuce</groupId> |
| <artifactId>lettuce-core</artifactId> |
| <version>5.0.4.RELEASE</version> |
| </dependency> |
| <dependency> |
| <groupId>junit</groupId> |
| <artifactId>junit</artifactId> |
| <version>4.12</version> |
| <scope>compile</scope> |
| </dependency> |
| <dependency> |
| <groupId>com.alibaba</groupId> |
| <artifactId>fastjson</artifactId> |
| <version>1.2.28</version> |
| </dependency> |
| </dependencies> |
点击查看详情
| package com.chen.redisdemo01.lettuce; |
| |
| import io.lettuce.core.RedisClient; |
| import io.lettuce.core.RedisFuture; |
| import io.lettuce.core.RedisURI; |
| import io.lettuce.core.api.StatefulRedisConnection; |
| import io.lettuce.core.api.async.RedisStringAsyncCommands; |
| import io.lettuce.core.api.reactive.RedisStringReactiveCommands; |
| import io.lettuce.core.api.sync.RedisCommands; |
| import io.lettuce.core.cluster.RedisClusterClient; |
| import io.lettuce.core.cluster.api.StatefulRedisClusterConnection; |
| import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands; |
| import org.junit.Test; |
| import java.time.Duration; |
| import java.util.Arrays; |
| import java.util.List; |
| |
| public class LettuceDemo { |
| |
| |
| @Test |
| public void test1() { |
| |
| RedisClient client = RedisClient.create("redis://192.168.96.192"); |
| |
| StatefulRedisConnection<String, String> connection = client.connect(); |
| |
| RedisCommands<String, String> redisCommands = connection.sync(); |
| redisCommands.set("name", "老五"); |
| String value = redisCommands.get("name"); |
| System.out.println("姓名:"+value); |
| |
| connection.close(); |
| |
| client.shutdown(); |
| } |
| |
| |
| @Test |
| public void test2() { |
| |
| RedisClient client = RedisClient.create("redis://192.168.96.192"); |
| |
| StatefulRedisConnection<String, String> connection = client.connect(); |
| |
| RedisCommands<String, String> redisCommands = connection.sync(); |
| redisCommands.sadd("k1", "v1"); |
| redisCommands.sadd("k1", "v2"); |
| String value = redisCommands.spop("k1"); |
| int num = Math.toIntExact(redisCommands.scard("k1")); |
| System.out.println("值:" + value + "+" + "集合个数:" + num); |
| |
| connection.close(); |
| |
| client.shutdown(); |
| } |
| |
| |
| @Test |
| public void test3() { |
| |
| RedisURI redisURI1 = RedisURI.create("redis://192.168.96.192:6379"); |
| RedisURI redisURI2 = RedisURI.Builder.redis("192.168.96.192").withPort(6381).withDatabase(0).build(); |
| List<RedisURI> list = Arrays.asList(redisURI1,redisURI2); |
| RedisClusterClient client = RedisClusterClient.create(list); |
| |
| client.setDefaultTimeout(Duration.ofSeconds(20)); |
| StatefulRedisClusterConnection<String, String> connect = client.connect(); |
| |
| RedisAdvancedClusterCommands<String, String> commands = connect.sync(); |
| commands.set("name1", "老五"); |
| String value = commands.get("name1"); |
| System.out.println("姓名:" + value); |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| connect.close(); |
| client.shutdown(); |
| } |
| |
| |
| @Test |
| public void test4() throws Exception { |
| |
| RedisClient client = RedisClient.create("redis://192.168.96.192:6379"); |
| StatefulRedisConnection<String, String> connection = client.connect(); |
| |
| |
| RedisStringAsyncCommands<String, String> asyncCommands = connection.async(); |
| asyncCommands.set("name1", "老五"); |
| RedisFuture<String> future = asyncCommands.get("name1"); |
| future.thenAccept((str) -> { |
| System.out.println("姓名:" + str); |
| }); |
| |
| System.out.println("END"); |
| Thread.sleep(10*1000); |
| connection.close(); |
| client.shutdown(); |
| } |
| |
| |
| @Test |
| public void test5() throws Exception { |
| |
| RedisClient client = RedisClient.create("redis://192.168.96.192:6379"); |
| |
| StatefulRedisConnection<String, String> connection = client.connect(); |
| |
| |
| RedisStringReactiveCommands<String, String> reactiveCommands = connection.reactive(); |
| reactiveCommands.set("name", "老五"); |
| reactiveCommands.get("name").subscribe((str) -> { |
| System.out.println("name:" + str); |
| }); |
| |
| System.out.println("END"); |
| Thread.sleep(10 * 1000); |
| connection.close(); |
| client.shutdown(); |
| } |
| |
| } |
| |
案例六
- 参考
- 案例为为
gitee/ chnx/ springboot / redis02
- 新建一个springboot项目,导入依赖
| <dependencies> |
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-web</artifactId> |
| </dependency> |
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-devtools</artifactId> |
| <scope>runtime</scope> |
| <optional>true</optional> |
| </dependency> |
| <dependency> |
| <groupId>org.projectlombok</groupId> |
| <artifactId>lombok</artifactId> |
| <optional>true</optional> |
| </dependency> |
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-test</artifactId> |
| <scope>test</scope> |
| </dependency> |
| |
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-data-redis</artifactId> |
| </dependency> |
| |
| |
| |
| |
| |
| </dependencies> |
| server: |
| port: 8080 |
| |
| spring: |
| redis: |
| database: 0 |
| host: 192.168.96.192 |
| password: 123456 |
| client-type: lettuce |
| lettuce: |
| pool: |
| max-idle: 8 |
| min-idle: 0 |
| max-active: 8 |
| max-wait: -1 |
| timeout: 30000 |
| |
| package com.chnq.redis01.config; |
| |
| import org.springframework.context.annotation.Bean; |
| import org.springframework.context.annotation.Configuration; |
| import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; |
| import org.springframework.data.redis.core.RedisTemplate; |
| import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; |
| import org.springframework.data.redis.serializer.StringRedisSerializer; |
| |
| @Configuration |
| public class RedisConfig { |
| |
| @Bean |
| public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory){ |
| RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); |
| redisTemplate.setKeySerializer(new StringRedisSerializer()); |
| redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); |
| redisTemplate.setHashKeySerializer(new StringRedisSerializer()); |
| redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); |
| redisTemplate.setConnectionFactory(redisConnectionFactory); |
| return redisTemplate; |
| } |
| |
| } |
| |
点击查看详情
| package com.chnq.redis01.utils; |
| |
| import java.util.Collection; |
| import java.util.List; |
| import java.util.Map; |
| import java.util.Set; |
| import java.util.concurrent.TimeUnit; |
| import org.springframework.beans.factory.annotation.Autowired; |
| import org.springframework.data.redis.core.RedisTemplate; |
| import org.springframework.stereotype.Component; |
| import org.springframework.util.CollectionUtils; |
| |
| @Component |
| public final class RedisUtils { |
| |
| @Autowired |
| private RedisTemplate<String, Object> redisTemplate; |
| |
| |
| |
| |
| |
| |
| |
| public boolean expire(String key, long time) { |
| try { |
| if (time > 0) { |
| redisTemplate.expire(key, time, TimeUnit.SECONDS); |
| } |
| return true; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| public long getExpire(String key) { |
| return redisTemplate.getExpire(key, TimeUnit.SECONDS); |
| } |
| |
| |
| |
| |
| |
| public boolean hasKey(String key) { |
| try { |
| return redisTemplate.hasKey(key); |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| @SuppressWarnings("unchecked") |
| public void del(String... key) { |
| if (key != null && key.length > 0) { |
| if (key.length == 1) { |
| redisTemplate.delete(key[0]); |
| } else { |
| redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key)); |
| } |
| } |
| } |
| |
| |
| |
| |
| |
| |
| public Object get(String key) { |
| return key == null ? null : redisTemplate.opsForValue().get(key); |
| } |
| |
| |
| |
| |
| |
| |
| public boolean set(String key, Object value) { |
| try { |
| redisTemplate.opsForValue().set(key, value); |
| return true; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| public boolean set(String key, Object value, long time) { |
| try { |
| if (time > 0) { |
| redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); |
| } else { |
| set(key, value); |
| } |
| return true; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| public long incr(String key, long delta) { |
| if (delta < 0) { |
| throw new RuntimeException("递增因子必须大于0"); |
| } |
| return redisTemplate.opsForValue().increment(key, delta); |
| } |
| |
| |
| |
| |
| |
| |
| public long decr(String key, long delta) { |
| if (delta < 0) { |
| throw new RuntimeException("递减因子必须大于0"); |
| } |
| return redisTemplate.opsForValue().increment(key, -delta); |
| } |
| |
| |
| |
| |
| |
| |
| |
| public Object hget(String key, String item) { |
| return redisTemplate.opsForHash().get(key, item); |
| } |
| |
| |
| |
| |
| |
| public Map<Object, Object> hmget(String key) { |
| return redisTemplate.opsForHash().entries(key); |
| } |
| |
| |
| |
| |
| |
| |
| public boolean hmset(String key, Map<String, Object> map) { |
| try { |
| redisTemplate.opsForHash().putAll(key, map); |
| return true; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| public boolean hmset(String key, Map<String, Object> map, long time) { |
| try { |
| redisTemplate.opsForHash().putAll(key, map); |
| if (time > 0) { |
| expire(key, time); |
| } |
| return true; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| public boolean hset(String key, String item, Object value) { |
| try { |
| redisTemplate.opsForHash().put(key, item, value); |
| return true; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| public boolean hset(String key, String item, Object value, long time) { |
| try { |
| redisTemplate.opsForHash().put(key, item, value); |
| if (time > 0) { |
| expire(key, time); |
| } |
| return true; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| public void hdel(String key, Object... item) { |
| redisTemplate.opsForHash().delete(key, item); |
| } |
| |
| |
| |
| |
| |
| |
| public boolean hHasKey(String key, String item) { |
| return redisTemplate.opsForHash().hasKey(key, item); |
| } |
| |
| |
| |
| |
| |
| |
| |
| public double hincr(String key, String item, double by) { |
| return redisTemplate.opsForHash().increment(key, item, by); |
| } |
| |
| |
| |
| |
| |
| |
| |
| public double hdecr(String key, String item, double by) { |
| return redisTemplate.opsForHash().increment(key, item, -by); |
| } |
| |
| |
| |
| |
| |
| |
| public Set<Object> sGet(String key) { |
| try { |
| return redisTemplate.opsForSet().members(key); |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return null; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| public boolean sHasKey(String key, Object value) { |
| try { |
| return redisTemplate.opsForSet().isMember(key, value); |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| public long sSet(String key, Object... values) { |
| try { |
| return redisTemplate.opsForSet().add(key, values); |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return 0; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| public long sSetAndTime(String key, long time, Object... values) { |
| try { |
| Long count = redisTemplate.opsForSet().add(key, values); |
| if (time > 0) |
| expire(key, time); |
| return count; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return 0; |
| } |
| } |
| |
| |
| |
| |
| |
| public long sGetSetSize(String key) { |
| try { |
| return redisTemplate.opsForSet().size(key); |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return 0; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| public long setRemove(String key, Object... values) { |
| try { |
| Long count = redisTemplate.opsForSet().remove(key, values); |
| return count; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return 0; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| public List<Object> lGet(String key, long start, long end) { |
| try { |
| return redisTemplate.opsForList().range(key, start, end); |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return null; |
| } |
| } |
| |
| |
| |
| |
| |
| public long lGetListSize(String key) { |
| try { |
| return redisTemplate.opsForList().size(key); |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return 0; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| public Object lGetIndex(String key, long index) { |
| try { |
| return redisTemplate.opsForList().index(key, index); |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return null; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| public boolean lSet(String key, Object value) { |
| try { |
| redisTemplate.opsForList().rightPush(key, value); |
| return true; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| public boolean lSet(String key, Object value, long time) { |
| try { |
| redisTemplate.opsForList().rightPush(key, value); |
| if (time > 0) |
| expire(key, time); |
| return true; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| public boolean lSet(String key, List<Object> value) { |
| try { |
| redisTemplate.opsForList().rightPushAll(key, value); |
| return true; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| public boolean lSet(String key, List<Object> value, long time) { |
| try { |
| redisTemplate.opsForList().rightPushAll(key, value); |
| if (time > 0) |
| expire(key, time); |
| return true; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| public boolean lUpdateIndex(String key, long index, Object value) { |
| try { |
| redisTemplate.opsForList().set(key, index, value); |
| return true; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| public long lRemove(String key, long count, Object value) { |
| try { |
| Long remove = redisTemplate.opsForList().remove(key, count, value); |
| return remove; |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return 0; |
| } |
| } |
| |
| } |
| |
| import com.chnq.redis01.utils.RedisUtils; |
| import org.junit.jupiter.api.Test; |
| import org.springframework.boot.test.context.SpringBootTest; |
| import org.springframework.data.redis.core.RedisTemplate; |
| import org.springframework.data.redis.core.ValueOperations; |
| import javax.annotation.Resource; |
| |
| @SpringBootTest |
| public class LettuceTest { |
| |
| @Resource |
| private RedisTemplate<String, String> redisTemplate; |
| |
| @Test |
| void testRedis(){ |
| ValueOperations<String, String> operations = redisTemplate.opsForValue(); |
| operations.set("hello1","world"); |
| String hello = operations.get("hello1"); |
| System.out.println(hello); |
| } |
| |
| } |
| |
| import lombok.Data; |
| |
| @Data |
| public class User { |
| private Integer id; |
| private String name; |
| private String age; |
| } |
| |
| import com.chnq.redis01.entity.User; |
| import com.chnq.redis01.utils.RedisUtils; |
| import org.springframework.web.bind.annotation.RequestBody; |
| import org.springframework.web.bind.annotation.RequestMapping; |
| import org.springframework.web.bind.annotation.RequestMethod; |
| import org.springframework.web.bind.annotation.RestController; |
| import javax.annotation.Resource; |
| |
| @RestController |
| @RequestMapping("/test") |
| public class TestController { |
| |
| |
| @Resource |
| private RedisUtils redisUtils; |
| |
| @RequestMapping(value = "/str1", method = RequestMethod.POST) |
| public String listAll(@RequestBody User user){ |
| String name = user.getName(); |
| String age = user.getAge(); |
| redisUtils.set(name, age); |
| return "success"; |
| } |
| |
| } |
| |
案例七
- 参考
- 案例为
gitee/ chenx/ redis-demo02
- 当前案例为mybatis plus + redis缓存
redis配置类
| import com.fasterxml.jackson.annotation.JsonAutoDetect; |
| import com.fasterxml.jackson.annotation.JsonTypeInfo; |
| import com.fasterxml.jackson.annotation.PropertyAccessor; |
| import com.fasterxml.jackson.databind.ObjectMapper; |
| import com.fasterxml.jackson.databind.SerializationFeature; |
| import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator; |
| import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; |
| import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; |
| import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; |
| import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; |
| import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; |
| import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; |
| import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; |
| import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; |
| import org.springframework.cache.CacheManager; |
| import org.springframework.cache.annotation.EnableCaching; |
| import org.springframework.context.annotation.Bean; |
| import org.springframework.context.annotation.Configuration; |
| import org.springframework.data.redis.cache.RedisCacheConfiguration; |
| import org.springframework.data.redis.cache.RedisCacheManager; |
| import org.springframework.data.redis.connection.RedisConnectionFactory; |
| import org.springframework.data.redis.core.RedisTemplate; |
| import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; |
| import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; |
| import org.springframework.data.redis.serializer.RedisSerializationContext; |
| import org.springframework.data.redis.serializer.StringRedisSerializer; |
| import java.time.Duration; |
| import java.time.LocalDate; |
| import java.time.LocalDateTime; |
| import java.time.format.DateTimeFormatter; |
| |
| |
| |
| |
| |
| |
| |
| @EnableCaching |
| @Configuration |
| public class RedisConfig { |
| |
| |
| private static final Long EXPIRE_TIME = 60L; |
| |
| |
| |
| |
| |
| @Bean(name = "stringByObjectTemplate") |
| public RedisTemplate<String, Object> stringByObjectTemplate(RedisConnectionFactory redisConnectionFactory) { |
| RedisTemplate<String,Object> template = new RedisTemplate<>(); |
| template.setConnectionFactory(redisConnectionFactory); |
| |
| |
| Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); |
| ObjectMapper objectMapper = new ObjectMapper(); |
| objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); |
| objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); |
| |
| |
| JavaTimeModule timeModule = new JavaTimeModule(); |
| timeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); |
| timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); |
| timeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); |
| timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); |
| objectMapper.registerModule(timeModule); |
| jsonRedisSerializer.setObjectMapper(objectMapper); |
| |
| |
| StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); |
| |
| template.setKeySerializer(stringRedisSerializer); |
| |
| template.setHashKeySerializer(stringRedisSerializer); |
| |
| template.setValueSerializer(jsonRedisSerializer); |
| |
| template.setHashValueSerializer(jsonRedisSerializer); |
| |
| template.afterPropertiesSet(); |
| return template; |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| @Bean |
| public CacheManager cacheManager(RedisConnectionFactory factory) { |
| |
| ObjectMapper objectMapper = new ObjectMapper() |
| .registerModule(new ParameterNamesModule()) |
| .registerModule(new Jdk8Module()) |
| .registerModule(new JavaTimeModule()); |
| objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance , ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); |
| objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); |
| |
| StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); |
| GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper); |
| |
| RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() |
| .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer)) |
| .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(genericJackson2JsonRedisSerializer)) |
| .entryTtl(Duration.ofSeconds(EXPIRE_TIME)); |
| |
| return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build(); |
| } |
| |
| } |
| |
案例八
- 参考为
bili_shiro_redis
使用redis作为缓存数据库存储权限信息
,核心代码如下
| package com.baizhi.springboot_jsp_shiro.shiro.cache; |
| |
| import com.baizhi.springboot_jsp_shiro.utils.ApplicationContextUtils; |
| import org.apache.shiro.cache.Cache; |
| import org.apache.shiro.cache.CacheException; |
| import org.springframework.data.redis.core.RedisTemplate; |
| import org.springframework.data.redis.serializer.StringRedisSerializer; |
| import java.util.Collection; |
| import java.util.Set; |
| |
| |
| public class RedisCache<k,v> implements Cache<k,v> { |
| |
| private String cacheName; |
| |
| public RedisCache() { |
| } |
| |
| public RedisCache(String cacheName) { |
| this.cacheName = cacheName; |
| } |
| |
| @Override |
| public v get(k k) throws CacheException { |
| System.out.println("get key:"+k); |
| return (v) getRedisTemplate().opsForHash().get(this.cacheName,k.toString()); |
| } |
| |
| @Override |
| public v put(k k, v v) throws CacheException { |
| System.out.println("put key: "+k); |
| System.out.println("put value:"+v); |
| getRedisTemplate().opsForHash().put(this.cacheName,k.toString(),v); |
| return null; |
| } |
| |
| @Override |
| public v remove(k k) throws CacheException { |
| System.out.println("=============remove============="); |
| return (v) getRedisTemplate().opsForHash().delete(this.cacheName,k.toString()); |
| } |
| |
| @Override |
| public void clear() throws CacheException { |
| System.out.println("=============clear=============="); |
| getRedisTemplate().delete(this.cacheName); |
| } |
| |
| @Override |
| public int size() { |
| return getRedisTemplate().opsForHash().size(this.cacheName).intValue(); |
| } |
| |
| @Override |
| public Set<k> keys() { |
| return getRedisTemplate().opsForHash().keys(this.cacheName); |
| } |
| |
| @Override |
| public Collection<v> values() { |
| return getRedisTemplate().opsForHash().values(this.cacheName); |
| } |
| |
| private RedisTemplate getRedisTemplate(){ |
| RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate"); |
| redisTemplate.setKeySerializer(new StringRedisSerializer()); |
| redisTemplate.setHashKeySerializer(new StringRedisSerializer()); |
| return redisTemplate; |
| } |
| |
| } |
| |
案例总结
- 案例3创建maven工程,使用jedis直接操作redis
| <dependency> |
| <groupId>redis.clients</groupId> |
| <artifactId>jedis</artifactId> |
| <version>3.2.0</version> |
| </dependency> |
- 案例5创建maven工程,使用lettuce直接操作redis
| <dependency> |
| <groupId>io.lettuce</groupId> |
| <artifactId>lettuce-core</artifactId> |
| <version>5.0.4.RELEASE</version> |
| </dependency> |
- 案例1创建spring boot项目,使用jedis连接redis,使用redisTemplate操作redis
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-data-redis</artifactId> |
| </dependency> |
- 案例2创建spring boot项目,使用lettuce连接redis,编写RedisUtils操作redis
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-data-redis</artifactId> |
| </dependency> |
- 案例6新建spring boot项目,使用lettuce连接redis,编写RedisUtils操作redis,
redis工具类更加全面
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-data-redis</artifactId> |
| </dependency> |
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术