Redis installed locally and tested with java

1. Install Redis on windows

1. Download Redis

Redis-x64-3.0.504.zip

2. Unzip to a certain directory, mine is in c:/apps/redis

3. Start the redis server.

C:\apps\redis>redis-server redis.windows.conf
                _._
           _.-``__ ''-._
      _.-``    `.  `_.  ''-._           Redis 3.0.504 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 39100
  `-._    `-._  `-./  _.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |           http://redis.io
  `-._    `-._`-.__.-'_.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |
  `-._    `-._`-.__.-'_.-'    _.-'
      `-._    `-.__.-'    _.-'
          `-._        _.-'
              `-.__.-'

[39100] 22 May 14:48:13.225 # Server started, Redis version 3.0.504
[39100] 22 May 14:48:13.229 * The server is now ready to accept connections on port 6379

4. Open another command window to start Redis command

The command is redis-cli.exe.  

set name hello is to keep a data whose name is name and value is hello

get name: is to take out the value of name

C:\apps\redis>redis-cli.exe
127.0.0.1:6379> set name hello
OK
127.0.0.1:6379> get name
"hello"
127.0.0.1:6379> get name

keys *: Take out all the keys that are said to be taken out.

127.0.0.1:6379> keys *
1) "Student:liu2"
2) "Student:liu5"
3) "Student"
4) "Student:liu3"
5) "name"

Use hmset to save data, use hget to get data

redis> HMSET myhash field1 "Hello" field2 "World"
"OK"
redis> HGET myhash field1
"Hello"
redis> HGET myhash field2
"World"

Use hmset to keep data. key is application

HMSET application sample.property.name1 "somevalue" sample.property.name2 "anothervalue"

Use hgetall to get application data

127.0.0.1:6379> hgetall application
1) "sample.property.name1"
2) "somevalue"
3) "sample.property.name2"
4) "anothervalue"

127.0.0.1:6379> hget application sample.property.name1
"somevalue"
127.0.0.1:6379> hget application sample.property.name2
"anothervalue"

 delete a key

127.0.0.1:6379> del certainkey
(integer) 1

Delete a batch of data according to a certain rule

KEYS "prefix:*" | xargs DEL

2. Java spring code test Redis

Add maven dependency in pom.xml

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.10</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<dependencies>
		
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
				<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
			<dependency>
		    <groupId>org.springframework.data</groupId>
		    <artifactId>spring-data-redis</artifactId>
		 </dependency>
		<dependency>
		    <groupId>redis.clients</groupId>
		    <artifactId>jedis</artifactId>
		    <type>jar</type>
		</dependency>

	</dependencies>

Create Configuration

@Configuration
public class RedisConfiguration {
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        return template;
    }
    
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory jedisConFactory
          = new JedisConnectionFactory();
        jedisConFactory.setHostName("localhost");
        jedisConFactory.setPort(6379);
        return jedisConFactory;
    }
}

Create the Student class

@RedisHash("Student")
public class Student implements Serializable {
  
    public enum Gender { 
        MALE, FEMALE
    }

    private String id;
    private String name;
    private Gender gender;
    private int grade;
    // ...
}

Create a Redis repository

@Repository
public interface StudentRepository extends CrudRepository<Student, String> {}
   

Create StudentDataService

@Service
public class StudentDataService {
    
    @Autowired
    private StudentRepository studentRepository;
    
    public Student saveStudent(String id) {
    	Student student = new Student(
		  id, "John Doe", Student.Gender.MALE, 1);
	    student = studentRepository.save(student);
	return student;
	
    }
    
    public Student getStudent(String id) {
	    Student retrievedStudent = 
		studentRepository.findById(id).get();
	    return retrievedStudent;
    }
    
    public Student updateStudent(Student student) {
	    Student dbStduent = this.getStudent(student.getId());
	
	    dbStduent.setName(student.getName());
	
	    dbStduent = studentRepository.save(dbStduent);
	    return dbStduent;
    }
    
    public void deleteStudent(Student student) {
	    studentRepository.deleteById(student.getId());
    }
    
    public List<Student> getAllStudents() {
	    List<Student> students = new ArrayList<>();
	    studentRepository.findAll().forEach(students::add);
	    return students;
    }

}

Finally create a StudentController for testing

@RestController
@RequestMapping("/student")
public class StudentContoller {
    
    @Autowired
    private StudentDataService studentDataService;
    
    
    @RequestMapping("/save/{id}")
    public String saveStudent(@PathVariable("id") String id) {
	//"Eng2015001"
	Student student = studentDataService.saveStudent(id);
	return student.toString();
    }
    
    @RequestMapping("/get/{id}")
    public String getStudent(@PathVariable("id") String id) {
	Student student = studentDataService.getStudent(id);
	return student.toString();
    }
    
    @RequestMapping("/delete/{id}")
    public String deleteStudent(@PathVariable("id")String id) {
	
	Student student = new Student();
	student.setId(id);
	
	studentDataService.deleteStudent(student);
	
	return "success";
	
    }
   @RequestMapping("/update/{id}")
    public String updateStudent(@PathVariable("id")  String id) {
	
	Student student = studentDataService.getStudent(id);
	student.setName("updated1");
	student = studentDataService.updateStudent(student);
	return student.toString();
	
    }
   
   @RequestMapping("/getAll")
   public String getAllStudents() {
       List<Student> students= studentDataService.getAllStudents();
       return students.toString();
       
   }
    
    

}

3. Keyspace Notifications of redis implements timing task queue

Revise redis.conf 或 redis.windows.conf 如果你用的是window版本的话

notify-keyspace-events Ex  // 打开此配置,其中Ex表示键事件通知里面的key过期事件,每当有过期键被删除时,会发送通知

When  notify-keyspace-events the option's argument is an empty string, the functionality is off. default is off

Write a listener

@Component
public class TaskTimeOutListener implements MessageListener {
  @Override
  public void onMessage(Message message, byte[] pattern) {
    String body = new String(message.getBody());
    String channel = new String(message.getChannel());
    System.out.println("Received task timeout event: "+body+" for key: " +  channel);
    String expiredKey = channel.split(":")[1];
    //implemented logic to discard task
  }
}

Configure the RedisMessageListenerContainer listening container

@Configuration
public class RedisJmsConfiguration {
    
  @Bean
  public RedisMessageListenerContainer redisMessageListenerContainer(
      RedisConnectionFactory connectionFactory,
      TaskTimeOutListener taskTimeoutListener) {
      System.out.println("===RedisMessageListenerContainer===" + taskTimeoutListener);
    RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
    
    listenerContainer.setConnectionFactory(connectionFactory);
   ChannelTopic channelTopic = new ChannelTopic("__keyevent@0__:expired");
   listenerContainer.addMessageListener(taskTimeoutListener,  channelTopic);
    listenerContainer.setErrorHandler(
        e -> System.out.println("Error in redisMessageListenerContainer" + e.getMessage()));
    return listenerContainer;
  }
}

Start your spring-boot project

Then, create a key on the client and set its timeout

set myname chhliu
expire myname 2
或者如下:
set myname chhliu px 2000

After 2 seconds you will find the following log

Received task timeout event: {} for key: {}myname__keyevent@0__:expired

Notice:

1. The above _keyevent@0_:expired is the topic corresponding to the key expiration event. The server will push the expiration event to this topic, and then the client will listen to this topic.

2. The content pushed to the topic by the key expiration event is only the key, but not the value, because once it expires, the value will no longer exist.

References

Introduction to Spring Data Redis | Baeldung

Redis keyspace notifications | Redis

Guess you like

Origin blog.csdn.net/keeppractice/article/details/130810220
Recommended